Passed
Pull Request — master (#31)
by Pieter Epeüs
01:54
created

Match   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 13
eloc 44
dl 0
loc 73
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
B checkOperators 0 42 7
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
22
        if (find && (this.operator === '!=' || this.operator === '<>')) {
23
            return true;
24
        }
25
26
        if (!find && !this.operator) {
27
            return true;
28
        }
29
30
        if (
31
            ((value > maxValue && maxValue !== null) || value > this.find) &&
32
            this.operator === '>'
33
        ) {
34
            return true;
35
        }
36
37
        if (
38
            ((value >= maxValue && maxValue !== null) || value >= this.find) &&
39
            this.operator === '>='
40
        ) {
41
            return true;
42
        }
43
44
        if (
45
            ((value < minValue && minValue !== null) || value < this.find) &&
46
            this.operator === '<'
47
        ) {
48
            return true;
49
        }
50
51
        if (
52
            ((value <= minValue && minValue !== null) || value <= this.find) &&
53
            this.operator === '<='
54
        ) {
55
            return true;
56
        }
57
58
        return false;
59
    }
60
61
    static create(original, key, find, operator) {
62
        const matcher = new Match(find, operator);
63
64
        return original.filter((item) => {
65
            let values = item[key];
66
67
            if (!values) {
68
                return false;
69
            }
70
71
            values = values.toString().split(',');
72
73
            return values.some(matcher.check.bind(matcher));
74
        });
75
    }
76
}
77
78
module.exports = function multifilter(original, key, find, operator) {
79
    return Match.create(original, key, find, operator);
80
};
81