Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
-3
rated 0 times [  1] [ 4]  / answers: 1 / hits: 22273  / 9 Years ago, sun, july 5, 2015, 12:00:00

Is there a better way instead of adding values of arrays up using a generator function as closure?



var sumArrays = function(){
var sum = 0;
return function*(){
while(true){
var array = yield sum;
if(array.__proto__.constructor === Array){
sum += array.reduce(function(val,val2){ return val+val2; });
}
else sum=0;
}
};
};

var gen = sumArrays();
// is this step required to make a generator or could it be done at least differently to spare yourself from doing this step?
gen = gen();

// sum some values of arrays up
console.log('sum: ',gen.next()); // Object { value=0, done=false}
console.log('sum: ',gen.next([1,2,3,4])); // Object { value=10, done=false}
console.log('sum: ',gen.next([6,7])); // Object { value=23, done=false}

// reset values
console.log('sum: ',gen.next(false)); // Object { value=0, done=false}
console.log('sum: ',gen.next([5])); // Object { value=5, done=false}

More From » generator

 Answers
21

This doesn't seem to be a problem generators are supposed to solve, so I would not use a generator here.



Directly using reduce (ES5) seems to be 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 multiple arrays across multiple function calls, then return a 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.


[#65922] Thursday, July 2, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jonrened

Total Points: 627
Total Questions: 114
Total Answers: 99

Location: Zimbabwe
Member since Thu, Jul 21, 2022
2 Years ago
jonrened questions
Mon, Nov 2, 20, 00:00, 4 Years ago
Tue, May 19, 20, 00:00, 4 Years ago
Tue, Jan 21, 20, 00:00, 4 Years ago
Thu, Nov 7, 19, 00:00, 5 Years ago
;