Completed
Push — master ( 8cf4a8...f9440e )
by Pieter Epeüs
17s queued 11s
created

Match   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 7
eloc 43
dl 0
loc 62
rs 10
c 0
b 0
f 0

4 Functions

Rating   Name   Duplication   Size   Complexity  
A constructor 0 4 1
A check 0 7 2
A checkOperators 0 31 1
A create 0 15 3
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);
0 ignored issues
show
Bug Best Practice introduced by
Apart from some edge-cases, it is generally advisable to use the strict comparison !== instead of !=.

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.

Loading history...
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