UNPKG

1.15 kBJavaScriptView Raw
1'use strict';
2
3const _ = require('lodash'),
4 clayUtils = require('clayutils'),
5 refProp = '_ref',
6 ignoredKeys = [
7 '_components',
8 '_componentSchemas',
9 '_pageData',
10 '_layoutRef',
11 refProp,
12 '_self',
13 'blockParams',
14 'filename',
15 'knownHelpers',
16 'locals',
17 'media',
18 'site',
19 'state',
20 'template'
21 ];
22
23/**
24 * deeply reduce a tree of components
25 * @param {object} result
26 * @param {*} tree
27 * @param {Function} fn to call when component object is found
28 * @returns {object}
29 */
30function deepReduce(result, tree, fn) {
31 if (_.isObject(tree) && tree[refProp] && clayUtils.isComponent(tree[refProp])) {
32 // we found a component!
33 fn(tree[refProp], tree);
34 }
35
36 if (_.isArray(tree)) {
37 // check for arrays first
38 _.each(tree, (item) => deepReduce(result, item, fn));
39 } else if (_.isObject(tree)) {
40 // then check for objects
41 _.forOwn(tree, function (val, key) {
42 if (_.head(key) !== '_' && !_.includes(ignoredKeys, key)) {
43 // don't iterate through any metadata
44 deepReduce(result, val, fn);
45 }
46 });
47 }
48 return result;
49}
50
51module.exports = deepReduce;