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
|
|
|
} |
27
|
|
|
|
|
|
|
|
28
|
|
|
if (!find && !this.operator) { |
29
|
|
|
return true; |
30
|
|
|
} |
31
|
|
|
|
|
|
|
|
32
|
|
|
if ((value > max(this.find) || value > this.find) && this.operator === '>') { |
|
|
|
|
33
|
|
|
return true; |
34
|
|
|
} |
35
|
|
|
|
|
|
|
|
36
|
|
|
if ((value >= max(this.find) || value >= this.find) && this.operator === '>=') { |
|
|
|
|
37
|
|
|
return true; |
38
|
|
|
} |
39
|
|
|
|
|
|
|
|
40
|
|
|
if ((value < min(this.find) || value < this.find) && this.operator === '<') { |
|
|
|
|
41
|
|
|
return true; |
42
|
|
|
} |
43
|
|
|
|
|
|
|
|
44
|
|
|
if ((value <= min(this.find) || value <= this.find) && this.operator === '<=') { |
|
|
|
|
45
|
|
|
return true; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
return false; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
static create(original, key, find, operator) { |
52
|
|
|
const matcher = new Match(find, operator); |
53
|
|
|
|
54
|
|
|
return original.filter((item) => { |
55
|
|
|
let values = item[key]; |
56
|
|
|
|
57
|
|
|
if (!values) { |
58
|
|
|
return false; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
values = values.toString().split(','); |
62
|
|
|
|
63
|
|
|
return values.some(matcher.check.bind(matcher)); |
64
|
|
|
}); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
module.exports = function multifilter(original, key, find, operator) { |
69
|
|
|
return Match.create(original, key, find, operator); |
70
|
|
|
}; |
71
|
|
|
|
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.