How to use a Generator Function In Javascript
A generator function can create an array of cumulative sums by iterating through the input array and yielding the cumulative sum at each step. By using the spread operator (…) with the generator function, you can generate the cumulative sum array efficiently.
Example: In this example we defines a generator function cumulativeSumGenerator that yields cumulative sums of an array. It iterates through array, updates the sum, and yields it. The result is converted to an array using the spread operator.
function* cumulativeSumGenerator(array) {
let sum = 0;
for (const element of array) {
sum += element;
yield sum;
}
}
const array = [1, 2, 3, 4, 5];
const cumulativeSumArray = [...cumulativeSumGenerator(array)];
console.log(cumulativeSumArray);
Output
[ 1, 3, 6, 10, 15 ]
How to Create an Array of Cumulative Sum in JavaScript ?
This article will demonstrate how to create an array containing a cumulative sum at each index from an array of integers in JavaScript.
The Cumulative Sum is defined as the partial sum total for the given sequence and all its previous values at a certain index. It is also known as the running sum as it keeps on adding the sum of all previous values. For instance, consider the below array:
Arr = [ 2, 7, 9, 4, 3 ]
The Cumulative sum at every index will be:
0 : 2
1 : 2 + 7 = 9
2 : 2 + 7 + 9 = 18
3 : 2 + 7 + 9 + 4 = 22
4 : 2 + 7 + 9 + 4 + 3 = 25
Hence, the resulting array will be:
Cumulative Sum = [ 2, 9, 18, 22, 25 ]