/
index.js
57 lines (42 loc) · 1.13 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
'use strict';
var isPlainObject = require('is-plain-object');
function filter(value, fn) {
if (Array.isArray(value)) {
return filterArray(value, fn);
} else if (isPlainObject(value)) {
return filterObject(value, fn);
}
return value;
}
function filterObject(obj, fn) {
var newObj = {};
var key;
var value;
for (key in obj) {
value = filter(obj[key], fn);
if (fn.call(obj, value, key, obj)) {
if (value !== obj[key] && !isCollection(value)) {
value = obj[key];
}
newObj[key] = value;
}
}
return newObj;
}
function filterArray(array, fn) {
var filtered = [];
array.forEach(function (value, index, array) {
value = filter(value, fn);
if (fn.call(array, value, index, array)) {
if (value !== array[index] && !isCollection(value)) {
value = array[index];
}
filtered.push(value);
}
});
return filtered;
}
function isCollection(value) {
return Array.isArray(value) || isPlainObject(value);
}
module.exports = filter;