This is not a problem that generators should solve, so I would not use a generator here.
Directly using reduce (ES5) seems more appropriate:
let sum = [1,2,3,4].reduce((sum, x) => sum + x);
As a function:
function sum(arr) { return arr.reduce((sum, x) => sum + x); }
If you really want to sum several arrays over several function calls, return the normal function:
function getArraySummation() { let total = 0; let reducer = (sum, x) => sum + x; return arr => total + arr.reduce(reducer); } let sum = getArraySummation(); console.log('sum:', sum([1,2,3])); // sum: 6 console.log('sum:', sum([4,5,6])); // sum: 15
Keep it simple.
Felix kling
source share