-
Notifications
You must be signed in to change notification settings - Fork 181
/
walkReduceEvaluables.js
55 lines (51 loc) · 1.97 KB
/
walkReduceEvaluables.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
import {
concat,
forEach,
isArray,
isNativeObject,
isObject,
resolve,
walk
} from '@serverless/utils'
import isEvaluable from '../variable/isEvaluable'
import isComponent from './isComponent'
const reduceWalkee = () => {
const visited = new Set()
return (accum, value, keys, iteratee, recur) => {
let result = accum
if (isEvaluable(value)) {
visited.add(value)
result = iteratee(result, value, keys)
value = resolve(value)
if (isComponent(value) || !isObject(value)) {
return result
}
}
if (isObject(value) && !visited.has(value)) {
if (isArray(value) || !isNativeObject(value)) {
visited.add(value)
forEach((childValue, childKdx) => {
if (!isComponent(childValue)) {
const newKeys = concat(keys, [childKdx])
result = recur(result, childValue, newKeys, iteratee)
}
}, value)
}
}
return result
}
}
/**
* Walk reduce the component's own evaluables (variables and resolvables). A component's "own" evaluables are determined by walking the component's properties until either a evaluable is encountered or another component instance is encountered. If another component instance is found the walk will not walk to that component's properties. If a evaluable is found it will be fed to the iteratee method along with the path to that evaluable.
*
* This method has cirrcular reference protection. It will not walk a property path more than once
*
* @function
* @param {Function} fn The iterator function. Receives three values, the accumulator and the current evaluable from the walk and the current set of keys from the entire depth of the walk.
* @param {*} accum The accumulator value.
* @param {Component} component The component to walk.
* @returns {*} The final, accumulated value.
*/
const walkReduceEvaluables = (iteratee, accum, component) =>
walk(reduceWalkee(), iteratee, accum, component, [])
export default walkReduceEvaluables