Created
November 1, 2018 22:29
-
-
Save rpgeeganage/c572a3367cdc2e997fc6eaed67419a0e to your computer and use it in GitHub Desktop.
ReduceRight 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
/** returns any type value */ | |
type CallBackReduceRight<T, R> = ( | |
accumulator: T | R, | |
value: T, | |
index?: number, | |
collection?: T[] | |
) => Promise<T | R>; | |
/** | |
* Async ReduceRight function | |
* | |
* @export | |
* @template T | |
* @template R | |
* @param {T[]} elements | |
* @param {CallBackReduceRight<T, R>} cb | |
* @param {R} [initialValue] | |
* @returns {Promise<T | R>} | |
*/ | |
async function aReduceRight<T, R>( elements: T[], cb: CallBackReduceRight<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 = elements.length - 1; | |
if (initialValue === undefined) { | |
reducedValue = elements[index] as T; | |
index--; | |
} else { | |
reducedValue = initialValue; | |
} | |
for (; index >= 0; 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 aReduceRight<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