Underscore.js _.iterators.accumulateWithReturn() method
Last Updated :
11 Apr, 2023
With the help of _.iterators.accumulateWithReturn() method, we can expect to return two values in an array when the iterator function is called the output of the current iteration is passed to the next iteration value by using this method.
Syntax:
_.iterators.accumulateWithReturn(iter, binaryFn, initial)
Return: Return the two values in an array to the iterator.
Example 1: In this example, we can see that by using _.iterators.accumulateWithReturn() method, we are able to expect the two values in an array whenever we call the iterator. It will always pass the result of the current iteration to the next one.
javascript
const _ = require( 'underscore-contrib' );
let iter = _.iterators.List([ "A" , "ABA" , "ABCBA" , "ABA" , "A" ]);
function calculateLength(geeky, element) {
return [element.length, 'Length of ' + element + 'is ' + element.length];
}
let gfg = _.iterators.accumulate(iter, calculateLength, 0);
for ( var i = 0; i < 5; i++) {
console.log(gfg());
}
|
Output:
[ 5, 'Length of Geeks is 5' ]
[ 3, 'Length of for is 3' ]
[ 5, 'Length of Geeks is 5' ]
Example 2:
javascript
const _ = require( 'underscore-contrib' );
let iter = _.iterators.List([ "A" , "ABA" , "ABCBA" , "ABA" , "A" ]);
function calculateLength(geeky, element) {
return [element.length, 'Length of ' + element + 'is ' + element.length];
}
let gfg = _.iterators.accumulate(iter, calculateLength, 0);
for ( var i = 0; i < 5; i++) {
console.log(gfg());
}
|
Output:
[ 1, 'Length of A is 1' ]
[ 3, 'Length of ABA is 3' ]
[ 5, 'Length of ABCBA is 5' ]
[ 3, 'Length of ABA is 3' ]
[ 1, 'Length of A is 1' ]
Share your thoughts in the comments
Please Login to comment...