-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
90 lines (76 loc) · 2.42 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
'use strict';
const flatten = require('flatten-unflatten').flatten;
let lowercase = (string) => {
return typeof string === 'string' ? string.toLowerCase() : string;
};
let filters = {
includes: (value, filter) => {
// No substring matching against `undefined`
if (typeof value === 'undefined') {
return false;
}
// No substring matching against `null`; only match against `null`
if ((value === null) || (filter === null)) {
return value === filter;
}
value = lowercase('' + value);
filter = lowercase('' + filter);
return value.indexOf(filter) !== -1;
},
gt: (value, filter) => {
return value > filter;
},
lt: (value, filter) => {
return value < filter;
},
};
function filterSearch(curr, search, comparator) {
curr = flatten(curr);
for (let key in search) {
if (!comparator[key]) {
comparator[key] = 'includes';
}
// search: {name: 123, city: basel}
// wenn object.name nicht vorhanden, nicht vergleichen und als nicht gefunden deklarieren
if (!curr[key] || !filters[comparator[key]](curr[key], search[key])) {
return false;
}
}
return true;
}
function filterAll(curr, search, comparator, searchAllValue) {
curr = flatten(curr, { arrays: true });
let found = true;
for (let key in search) {
if (!comparator[key]) {
comparator[key] = 'includes';
}
// search: {name: 123, city: basel}
// wenn object.name nicht vorhanden, nicht vergleichen und als nicht gefunden deklarieren
if (!curr[key] || !filters[comparator[key]](curr[key], search[key])) {
found = false;
}
}
for (let key in curr) {
if (filters.includes(curr[key], searchAllValue) && found) {
return true
}
}
return false;
}
module.exports = (array, search, comparator, additionalFilters) => {
additionalFilters && Object.assign(filters, additionalFilters);
search = flatten(search);
comparator = flatten(comparator);
if (search.$) {
let searchAllValue = search.$;
delete search.$;
return array.filter(item => {
return filterAll(item, search, comparator, searchAllValue);
});
} else {
return array.filter(item => {
return filterSearch(item, search, comparator);
});
}
};