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