-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcollection.js
63 lines (54 loc) · 1.18 KB
/
collection.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
'use strict';
const any = require('any');
const iterator = require('../iterator');
const utils = require('../utils');
/**
* Returns `true` if `value` exists in the given string, array
* or object. See [any] for documentation.
*
* @param {*} `value`
* @param {*} `target`
* @param {Object} `options`
* @api public
*/
exports.any = any;
/**
* Filter the given array or object to contain only the matching values.
*
* ```js
* <%= filter(['foo', 'bar', 'baz']) %>
* //=> '["a", "b", "c"]'
* ```
*
* @param {Array} `arr`
* @return {Array}
* @api public
*/
exports.filter = (val, fn, context) => {
if (utils.isEmpty(val)) return '';
let iter = () => {};
if (typeof fn === 'string') {
let prop = fn;
iter = target => {
return typeof target === 'string' ? target === prop : target[prop];
};
} else {
iter = iterator(fn, context);
}
if (typeof val === 'string') {
return iter(val);
}
if (Array.isArray(val)) {
return val.filter(iter);
}
if (utils.isObject(val)) {
let obj = val;
let res = {};
for (let key in obj) {
if (obj.hasOwnProperty(key) && iter(key)) {
res[key] = obj[key];
}
}
return res;
}
};