Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to sum arrays using ECMASCRIPT 6 Generator/Functions

Tags:

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} 
like image 233
Blauharley Avatar asked Jul 05 '15 11:07

Blauharley


People also ask

How do you sum up an array in Javascript?

To get the sum of an array of numbers:Use the Array. reduce() method to iterate over the array. Set the initial value in the reduce method to 0 . On each iteration, return the sum of the accumulated value and the current number.

When should we use generators in ES6?

In a normal function, there is only one entry point: the invocation of the function itself. A generator allows you to pause the execution of a function and resume it later. Generators are useful when dealing with iterators and can simplify the asynchronous nature of Javascript.

How will you get the sum from a function in Javascript?

sum() function in D3. js is used to return the sum of the given array's elements. If the array is empty then it returns 0. Parameters: This function accepts a parameters Array which is an array of elements whose sum are to be calculated.


1 Answers

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.

like image 197
Felix Kling Avatar answered Sep 21 '22 18:09

Felix Kling