Skip to content

Instantly share code, notes, and snippets.

@rpgeeganage
Created November 1, 2018 22:29
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/c572a3367cdc2e997fc6eaed67419a0e to your computer and use it in GitHub Desktop.
Save rpgeeganage/c572a3367cdc2e997fc6eaed67419a0e to your computer and use it in GitHub Desktop.
ReduceRight method
/** 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