Js recursive summation

A={
    value:1,
    items:[A,A,A] //itemsA
}

is there any good way to find the sum of all the value in object A

Feb.27,2021

function sum(arr) {
  var _sum = 0;
  arr.forEach(v => _sum += v);
  return _sum;
}

function sumA(A) {
  if(A.items && A.items.length) {
    return sum([A.value].concat(a.items.map(sumA)));
  } else {
    return A.value;
  }
}

finally call sumA to sum. I wonder if this meets your requirements?

The concat in

sumA is for tail recursive optimization, but I'm not sure if you can do tail recursive optimization by writing this. A more understandable version:

function sumA(A) {
  if(A.items && A.items.length) {
    var sum = A.value;
    for(let a of A.items) {
      sum += sumA(a);
    }
    return sum;
  } else {
    return A.value;
  }
}
Menu