The reduce()
method of Iterator instances is similar to Array.prototype.reduce: it executes a user-supplied "reducer" callback function on each element produced by the iterator, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements is a single value.
Syntax
reduce(callbackFn)
reduce(callbackFn, initialValue)
Parameters
callbackFn
- : A function to execute for each element produced by the iterator. Its return value becomes the value of the
accumulator
parameter on the next invocation ofcallbackFn
. For the last invocation, the return value becomes the return value ofreduce()
. The function is called with the following arguments:accumulator
- : The value resulting from the previous call to
callbackFn
. On the first call, its value isinitialValue
if the latter is specified; otherwise its value is the first element of the iterator.
- : The value resulting from the previous call to
currentValue
- : The value of the current element. On the first call, its value is the first element of the iterator if
initialValue
is specified; otherwise its value is the second element.
- : The value of the current element. On the first call, its value is the first element of the iterator if
currentIndex
- : The index position of
currentValue
. On the first call, its value is0
ifinitialValue
is specified, otherwise1
.
- : The index position of
- : A function to execute for each element produced by the iterator. Its return value becomes the value of the
initialValue
- : A value to which
accumulator
is initialized the first time the callback is called. IfinitialValue
is specified,callbackFn
starts executing with the first element ascurrentValue
. IfinitialValue
is not specified,accumulator
is initialized to the first element, andcallbackFn
starts executing with the second element ascurrentValue
. In this case, if the iterator is empty (so that there's no first value to return asaccumulator
), an error is thrown.
- : A value to which
Return value
The value that results from running the "reducer" callback function to completion over the entire iterator.
Exceptions
- TypeError
- : Thrown if the iterator contains no elements and
initialValue
is not provided.
- : Thrown if the iterator contains no elements and
Description
See Array.prototype.reduce for details about how reduce()
works. Unlike most other iterator helper methods, it does not work well with infinite iterators, because it is not lazy.
Examples
Using reduce()
The following example creates an iterator that yields terms in the Fibonacci sequence, and then sums the first ten terms:
function* fibonacci() {
let current = 1;
let next = 1;
while (true) {
yield current;
[current, next] = [next, current + next];
}
}
console.log(
fibonacci()
.take(10)
.reduce((a, b) => a + b),
); // 143