-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
95 lines (88 loc) · 2 KB
/
index.js
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
var type = require('type-of');
module.exports = toBoolFunction;
/**
* Convert various possible things into a match function
*
* @param {Any} [selector]
* @param {Any} condition
* @return {Function}
*/
function toBoolFunction(selector, condition) {
if (arguments.length == 2) {
selector = toBoolFunction(selector);
condition = toBoolFunction(condition);
return function () {
return condition(selector.apply(this, arguments));
};
} else {
condition = selector;
}
var alternate = false;
try {
switch (type(condition)) {
case 'regexp':
alternate = regexpToFunction(condition);
break;
case 'string':
alternate = stringToFunction(condition);
break;
case 'function':
alternate = condition;
break;
case 'object':
alternate = objectToFunction(condition);
break;
}
} catch (ex) {
//ignore things that aren't valid functions
}
return function (val) {
return (val === condition) ||
(alternate && alternate.apply(this, arguments));
}
}
/**
* Convert `regexp` into a match funciton
*
* @param {Regexp} regexp
* @return {Function}
* @api private
*/
function regexpToFunction(regexp) {
return function (val) {
return regexp.test(val);
};
}
/**
* Convert `obj` into a match function.
*
* @param {Object} obj
* @return {Function}
* @api private
*/
function objectToFunction(obj) {
var fns = Object.keys(obj)
.map(function (key) {
return toBoolFunction(key, obj[key]);
});
return function(o){
for (var i = 0; i < fns.length; i++) {
if (!fns[i](o)) return false;
}
return true;
}
}
/**
* Convert property `str` to a function.
*
* @param {String} str
* @return {Function}
* @api private
*/
function stringToFunction(str) {
// immediate such as "> 20"
if (/^ *\W+/.test(str)) return new Function('_', 'return _ ' + str);
// properties such as "name.first" or "age > 18"
var fn = new Function('_', 'return _.' + str);
return fn
}