Skip to content

Instantly share code, notes, and snippets.

@rpgeeganage
Created November 1, 2018 22:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rpgeeganage/fc85d614dad94dc51611cced59c7e79c to your computer and use it in GitHub Desktop.
Save rpgeeganage/fc85d614dad94dc51611cced59c7e79c to your computer and use it in GitHub Desktop.
Reduce method
// Signature of the callback
type CallBackReduce<T, R> = (
accumulator: R,
value: T,
index?: number,
collection?: T[]
) => Promise<R>;
/**
* Async Reduce function
*
* @export
* @template T
* @template R
* @param {T[]} elements
* @param {CallBackReduce<T, R>} cb
* @param {R} [initialValue]
* @returns {Promise<R>}
*/
async function aReduce<T, R>( elements: T[], cb: CallBackReduce<T, R>, initialValue?: R ): Promise<T | R> {
if (!elements.length && initialValue === undefined) {
throw new Error('Reduce of empty array with no initial value');
}
let reducedValue: T | R;
let index = 0;
if (initialValue === undefined) {
reducedValue = elements[0] as T;
index++;
} else {
reducedValue = initialValue;
}
for (; index < elements.length; index++) {
reducedValue = await cb(reducedValue, elements[index], index, elements);
}
return reducedValue;
}
// You can use as follows
const array = [1, 2, 3, 4];
const output = await aReduce<number, string>(array, async (acc, i,) => {
return Promise.resolve(`${acc}${i.toString(10)}`);
}, '');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment