This repository was archived by the owner on Jun 7, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
81 lines (65 loc) · 1.52 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
'use strict'
module.exports = scrump
function scrump (
node,
criteria,
{
all = true,
array = true,
recursive = true,
visited = new Set()
} = {}
) {
if (visited.has(node)) {
return []
}
visited.add(node)
if (match(node, criteria)) {
return [ node ]
}
try {
if (Array.isArray(node) && array) {
return node.reduce((results, item) => {
return recur(results, item, criteria, { all, array, recursive, visited })
}, [])
}
if (isObject(node) && recursive) {
return Object.keys(node).reduce((results, key) => {
return recur(results, node[key], criteria, { all, visited })
}, [])
}
return []
} catch (error) {
if (error instanceof Error) {
throw error
}
// `throw` has been abused to stop walking nodes when we have the result
return error
}
}
function match (node, criteria) {
if (! isObject(node)) {
if (node === criteria) {
return true
}
return false
}
if (! isObject(criteria)) {
return false
}
return Object.keys(criteria).every(criteriaKey => {
return Object.keys(node).some(nodeKey => {
return match(node[nodeKey], criteria[criteriaKey])
})
})
}
function recur (results, node, criteria, options) {
if (! options.all && results.length > 0) {
// abuse `throw` to stop walking nodes when we have the result
throw results
}
return results.concat(scrump(node, criteria, options))
}
function isObject (node) {
return node && typeof node === 'object'
}