const valueList = {
prop: 'prop1',
value: 150,
children: [
{
prop: 'prop1',
value: 14
}, {
prop: 'prop1',
value: 10,
children: [
{
prop: 'prop1',
value: 14
}, {
prop: 'prop1',
value: 10,
children: []
},{
prop: 'prop1',
value: 110,
}
]
},{
prop: 'prop1',
value: 110,
}
]
}
const sum = data =>
(data instanceof Array ? data : [ data ]).reduce((acc, n) => {
return acc + n.value + sum(n.children || []);
}, 0);
const sum = function(data) {
const stack = [];
let result = 0;
for (let [ i, arr ] = this(data); ++i < arr.length || stack.length;) {
if (i === arr.length) {
[ i, arr ] = stack.pop();
} else {
result += arr[i].value;
stack.push([ i, arr ]);
[ i, arr ] = this(arr[i].children || []);
}
}
return result;
}.bind(x => [ -1, Array.isArray(x) ? x : [ x ] ]);
sum(valueList) // 418
sum(valueList.children) // 268