reduce
The reduce() function reduces a generator to a single value by applying an accumulator function to each element. It also allows early exit with exit().
Interactive example
Syntax
Classic signature
typescript
function reduce<
GenericElement extends unknown,
GenericReduceFrom extends GeneratorEligibleReduceFromValue,
>(
iterator: Iterable<GenericElement>,
startValue: GenericReduceFrom,
theFunction: (
params: GeneratorReduceFunctionParams<
GenericElement,
GeneratorReduceFromValue<GenericReduceFrom>
>
) => GeneratorReduceExitOrNext<GeneratorReduceFromValue<GenericReduceFrom>>
): GeneratorReduceFromValue<GenericReduceFrom>Curried signature
typescript
function reduce<
GenericElement extends unknown,
GenericReduceFrom extends GeneratorEligibleReduceFromValue,
>(
startValue: GenericReduceFrom,
theFunction: (
params: GeneratorReduceFunctionParams<
GenericElement,
GeneratorReduceFromValue<GenericReduceFrom>
>
) => GeneratorReduceExitOrNext<GeneratorReduceFromValue<GenericReduceFrom>>
): (iterator: Iterable<GenericElement>) => GeneratorReduceFromValue<GenericReduceFrom>Parameters
iterator: The generator to reducestartValue: Initial accumulator value (useDGenerator.reduceFrom()for objects)theFunction: Reduction function that receives:element: The current elementindex: The element indexlastValue: The previous accumulated valuenext(value): Continues with a new accumulated valueexit(value): Ends and returns the valuenextWithObject(obj1, obj2): Merges two objects (available iflastValueis an object)
Return value
The final accumulated value.
See also
asyncReduce- Asynchronous version of reducemap- Transforms the elements of a generatorfilter- Filters the elements of a generator
