-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
39 lines (34 loc) · 992 Bytes
/
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
const entries = require('object.entries')
function targetFor (source, destructive) {
if (Array.isArray(source)) {
return destructive ? source : []
} else if (typeof source === 'object') {
return destructive ? source : {}
}
}
module.exports = function breadthFilter (root, fn, destructive) {
const target = targetFor(root, destructive)
if (!target) return root
const queue = [[ root, target, [] ]]
const seen = new Set()
let item
while (item = queue.shift()) {
const [ source, target, path ] = item
for (const [ key, value ] of entries(source)) {
const fieldPath = path.concat(key)
const newTarget = targetFor(value, destructive)
if (newTarget) {
if (!seen.has(value)) {
seen.add(value)
} else {
continue
}
target[key] = newTarget
queue.push([ value, target[key], fieldPath ])
} else {
target[key] = fn(value, key, fieldPath)
}
}
}
return target
}