forked from mmckelvy/walk-object
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
35 lines (29 loc) · 963 Bytes
/
index.js
File metadata and controls
35 lines (29 loc) · 963 Bytes
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
const OBJECT_CONSTRUCTORS = ['Function', 'Object']
/**
* @param {object} root - The object to walk
* @param {function} fn - A function to call on each node
*/
export default function walkObject(root, fn)
{
async function walk(value, location = [])
{
// Value is an array, call walk on each item in the array
if(Array.isArray(value))
return await Promise.all([
fn({value, location}),
...value.map((el, j) => walk(el, [...location, j]))
])
// Value is an object, walk the keys of the object
if(value && OBJECT_CONSTRUCTORS.includes(value.constructor.name))
{
const entries = Object.entries(value)
return await Promise.all([
fn({value, location}),
...entries.map(([key, value]) => walk(value, [...location, key]))
])
}
// We've reached a leaf node, call fn on the leaf with the location
return await fn({value, location, isLeaf: true})
}
return walk(root)
}