A
A
alex9999212019-11-07 17:53:12
JavaScript
alex999921, 2019-11-07 17:53:12

Is it possible to combine recursion with pure functions?

You need to find the average value of the value fields, use pure functions.
I read a lot of material and I don’t understand how it can be done with recursion.
I'm probably doing the object traversal with recursion incorrectly, but how else can I make req (obj) return the value field of each branch.

var obj={value:14,children:[{value:33,children:[{value:9,children:[{value:35},{value:69},{value:6}]},{value:47,children:[{value:4}]},{value:52,children:[{value:74},{value:55}]}]},{value:88,children:[{value:71,children:[{value:35}]},{value:6,children:[{value:74}]},{value:26,children:[{value:80},{value:42}]}]}]};

const fnCounter = start => {
  let counter = start;
  return () => counter++;
};

const avarageQuantity = fnCounter(0);

let sum = 0;

const req = objItem => {
  (objItem.children || []).map(req);
  sum = sum + obj.value;
  avarageQuantity();
};

req(obj);
console.log(sum / avarageQuantity());/code>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-11-07
@alex999921

const count = obj =>
  (obj.children || []).reduce((acc, n) => {
    const c = count(n);
    acc.num += c.num;
    acc.sum += c.sum;
    return acc;
  }, { num: 1, sum: obj.value });


const c = count(obj);
const average = c.sum / c.num;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question