-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
46 lines (39 loc) · 1.23 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
const entries = require('object.entries')
function defaultOnArray () { return [] }
function defaultOnObject () { return {} }
function targetFor (source, key, fieldPath, isNew, {
onArray = defaultOnArray,
onObject = defaultOnObject
} = {}) {
if (Array.isArray(source)) {
return onArray(source, key, fieldPath, isNew)
} else if (source !== null && typeof source === 'object') {
return onObject(source, key, fieldPath, isNew)
}
}
module.exports = function breadthFilter (root, opts = {}) {
const { onValue } = opts
const target = targetFor(root, null, [], true, opts)
if (!target) return root
const queue = [[ root, target, [] ]]
const seen = new Set([ root ])
let item
while (item = queue.shift()) {
const [ source, target, path ] = item
for (const [ key, value ] of entries(source)) {
const fieldPath = path.concat(key)
const isNew = !seen.has(value)
if (isNew) seen.add(value)
const newTarget = targetFor(value, key, fieldPath, isNew, opts)
if (newTarget) {
target[key] = newTarget
if (isNew) {
queue.push([ value, target[key], fieldPath ])
}
} else {
target[key] = onValue(value, key, fieldPath)
}
}
}
return target
}