-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathKeyFilter.js
More file actions
47 lines (36 loc) · 1.43 KB
/
KeyFilter.js
File metadata and controls
47 lines (36 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
var EventEmitter = require('events').EventEmitter
var util = require('util')
var R = require('ramda')
var isString = R.compose(R.equals('String'), R.type)
var isFunction = R.compose(R.equals('Function'), R.type)
var _ = require('lodash')
function KeyFilter(_options) {
var options = _.merge({}, { exclude: [], include: [] }, _options)
var self = this
this.handle = function(event) {
self.emit('message', R.pipe(R.pickBy(notExcluded), R.pickBy(included))(event))
}
function notExcluded(value, key) {
return consider(value, key, R.none, options.exclude)
}
function included(value, key) {
return consider(value, key, R.any, options.include)
}
function consider(value, key, includeOrExclude, items) {
if (items.length === 0) return true
return includeOrExclude(function(testable) {
return testable.test(key)
}, items)
}
function ensureRegExp(testable) {
if (isString(testable)) return new RegExp('\\b' + testable + '\\b', 'i')
if (isFunction(testable.test)) return testable
if (isFunction(testable)) return { test: testable }
throw new Error('Predicates must be a string, regular expression or function')
}
options.exclude = R.map(ensureRegExp, options.exclude)
options.include = R.map(ensureRegExp, options.include)
EventEmitter.call(this);
}
util.inherits(KeyFilter, EventEmitter)
module.exports = KeyFilter