Function: reduce()
reduce<
ElementType
,MappedType
>(iterable
:IterableResolvable
<ElementType
>,callbackFn
: (accumulator
:MappedType
,currentValue
:ElementType
,currentIndex
:number
) =>MappedType
,initialValue
?:MappedType
):MappedType
Consumes the iterable and reduces it to the reducer function's result.
Type Parameters
Type Parameter |
---|
ElementType |
MappedType |
Parameters
Parameter | Type | Description |
---|---|---|
iterable | IterableResolvable <ElementType > | An iterator to reduce. |
callbackFn | (accumulator : MappedType , currentValue : ElementType , currentIndex : number ) => MappedType | 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 of callbackFn . For the last invocation, the return value becomes the return value of reduce() . |
initialValue ? | MappedType | A value to which accumulator is initialized the first time the callback is called. If initialValue is specified, callbackFn starts executing with the first element as currentValue . If initialValue is not specified, accumulator is initialized to the first element, and callbackFn starts executing with the second element as currentValue . In this case, if the iterator is empty (so that there's no first value to return as accumulator ), an error is thrown. |
Returns
MappedType
Example
import { reduce } from '@sapphire/iterator-utilities';
const iterable = [1, 2, 3, 4, 5];
console.log(reduce(iterable, (accumulator, currentValue) => accumulator + currentValue));
// Output: 15
Remarks
If initialValue
is not provided, the first element of the iterator is used as the initial value of accumulator
,
consuming the first element.
Defined in
projects/utilities/packages/iterator-utilities/src/lib/reduce.ts:33