1
|
|
|
const min = require('./min.js'); |
2
|
|
|
const max = require('./max.js'); |
3
|
|
|
|
4
|
|
|
class Match { |
5
|
|
|
constructor(find, operator) { |
6
|
|
|
this.find = find; |
7
|
|
|
this.operator = operator || null; |
8
|
|
|
} |
9
|
|
|
|
10
|
|
|
check(value) { |
11
|
|
|
if (Array.isArray(this.find)) { |
12
|
|
|
return this.checkOperators(value, this.find.indexOf(value) < 0); |
13
|
|
|
} |
14
|
|
|
|
15
|
|
|
return this.checkOperators(value, value != this.find); |
|
|
|
|
16
|
|
|
} |
17
|
|
|
|
18
|
|
|
checkOperators(value, find) { |
19
|
|
|
if ( |
20
|
|
|
find && |
21
|
|
|
(this.operator == true || |
|
|
|
|
22
|
|
|
this.operator == '!=' || |
|
|
|
|
23
|
|
|
this.operator == '<>') |
|
|
|
|
24
|
|
|
) { |
25
|
|
|
return true; |
26
|
|
|
} else if (!find && !this.operator) { |
|
|
|
|
27
|
|
|
return true; |
28
|
|
|
} else if (value > max(this.find) && this.operator == '>') { |
|
|
|
|
29
|
|
|
return true; |
30
|
|
|
} else if (value >= max(this.find) && this.operator == '>=') { |
|
|
|
|
31
|
|
|
return true; |
32
|
|
|
} else if (value < min(this.find) && this.operator == '<') { |
|
|
|
|
33
|
|
|
return true; |
34
|
|
|
} else if (value <= min(this.find) && this.operator == '<=') { |
|
|
|
|
35
|
|
|
return true; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
return false; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
static create(original, key, find, operator) { |
42
|
|
|
const matcher = new Match(find, operator); |
43
|
|
|
|
44
|
|
|
return original.filter((item) => { |
45
|
|
|
let values = item[key]; |
46
|
|
|
|
47
|
|
|
if (!values) { |
48
|
|
|
return false; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
values = values.toString().split(','); |
52
|
|
|
|
53
|
|
|
return values.some(matcher.check.bind(matcher)); |
54
|
|
|
}); |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
module.exports = function multifilter(original, key, find, operator) { |
59
|
|
|
return Match.create(original, key, find, operator); |
60
|
|
|
}; |
61
|
|
|
|
The loose comparison such as
==
or!=
might produce some weird results for some values, unless you explicitly want to have this behavior here, better use the strict alternative.Learn more about loose comparison in Javascript.