forked from vuejs/vue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharray-filters.js
104 lines (98 loc) · 2.37 KB
/
array-filters.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
var _ = require('../util')
var Path = require('../parsers/path')
var toArray = require('../directives/public/for')._postProcess
/**
* Filter filter for arrays
*
* @param {String} searchKey
* @param {String} [delimiter]
* @param {String} dataKey
*/
exports.filterBy = function (arr, search, delimiter /* ...dataKeys */) {
arr = toArray(arr)
if (search == null) {
return arr
}
if (typeof search === 'function') {
return arr.filter(search)
}
// cast to lowercase string
search = ('' + search).toLowerCase()
// allow optional `in` delimiter
// because why not
var n = delimiter === 'in' ? 3 : 2
// extract and flatten keys
var keys = _.toArray(arguments, n).reduce(function (prev, cur) {
return prev.concat(cur)
}, [])
var res = []
var item, key, val, j
for (var i = 0, l = arr.length; i < l; i++) {
item = arr[i]
val = (item && item.$value) || item
j = keys.length
if (j) {
while (j--) {
key = keys[j]
if ((key === '$key' && contains(item.$key, search)) ||
contains(Path.get(val, key), search)) {
res.push(item)
break
}
}
} else if (contains(item, search)) {
res.push(item)
}
}
return res
}
/**
* Filter filter for arrays
*
* @param {String} sortKey
* @param {String} reverse
*/
exports.orderBy = function (arr, sortKey, reverse) {
arr = toArray(arr)
if (!sortKey) {
return arr
}
var order = (reverse && reverse < 0) ? -1 : 1
// sort on a copy to avoid mutating original array
return arr.slice().sort(function (a, b) {
if (sortKey !== '$key') {
if (_.isObject(a) && '$value' in a) a = a.$value
if (_.isObject(b) && '$value' in b) b = b.$value
}
a = _.isObject(a) ? Path.get(a, sortKey) : a
b = _.isObject(b) ? Path.get(b, sortKey) : b
return a === b ? 0 : a > b ? order : -order
})
}
/**
* String contain helper
*
* @param {*} val
* @param {String} search
*/
function contains (val, search) {
var i
if (_.isPlainObject(val)) {
var keys = Object.keys(val)
i = keys.length
while (i--) {
if (contains(val[keys[i]], search)) {
return true
}
}
} else if (_.isArray(val)) {
i = val.length
while (i--) {
if (contains(val[i], search)) {
return true
}
}
} else if (val != null) {
return val.toString().toLowerCase().indexOf(search) > -1
}
}