Created
November 1, 2018 22:25
-
-
Save rpgeeganage/fc85d614dad94dc51611cced59c7e79c to your computer and use it in GitHub Desktop.
Reduce method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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