Skip to content

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 reduce
  • startValue: Initial accumulator value (use DGenerator.reduceFrom() for objects)
  • theFunction: Reduction function that receives:
    • element: The current element
    • index: The element index
    • lastValue: The previous accumulated value
    • next(value): Continues with a new accumulated value
    • exit(value): Ends and returns the value
    • nextWithObject(obj1, obj2): Merges two objects (available if lastValue is an object)

Return value

The final accumulated value.

See also

  • asyncReduce - Asynchronous version of reduce
  • map - Transforms the elements of a generator
  • filter - Filters the elements of a generator

Sources

Released under the MIT license.