// sink/reduce.ts /* * Copyright (c) 2021-2026 Check Digit, LLC * * This code is licensed under the MIT license (see LICENSE.txt for details). */ import asyncerator, { type Asyncerator } from '../asyncerator.ts'; /** * Calls the specified callback function for all the elements in a stream. The return value of the callback function * is the accumulated result, and is provided as an argument in the next call to the callback function. * Equivalent to the Javascript Array.reduce() method. * * @param reduceFunction The reduce method calls the reduceFunction function one time for each element in the stream. * @param initialValue If initialValue is specified, it is used as the previousValue to start the accumulation. * Otherwise, the initial previousValue will be undefined. */ export type ReduceFunction = ( previousValue: Output, currentValue: Input, currentIndex: number, ) => Output; export default function ( reduceFunction: ReduceFunction, initialValue?: Input, ): (iterator: Asyncerator) => Promise; export default function ( reduceFunction: ReduceFunction, initialValue?: Output, ): (iterator: Asyncerator) => Promise; export default function ( // eslint-disable-next-line sonarjs/use-type-alias reduceFunction: ReduceFunction, initialValue?: Input | Output, ): (iterator: Asyncerator) => Promise { return async function ( iterator: Asyncerator, ): Promise { let accumulator: Output | Input | undefined = initialValue; let currentIndex = 0; for await (const chunk of asyncerator(iterator)) { accumulator = reduceFunction(accumulator, chunk, currentIndex++); } return accumulator; }; }