Skip to content

Instantly share code, notes, and snippets.

@mattpodwysocki
Created May 4, 2017 19:44
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 mattpodwysocki/d1489932e0a8f52ac3f486e46eacf45f to your computer and use it in GitHub Desktop.
Save mattpodwysocki/d1489932e0a8f52ac3f486e46eacf45f to your computer and use it in GitHub Desktop.
'use strict';
export async function reduce<T>(
source: AsyncIterable<T>,
accumulator: (acc: T, value: T, index: number) => T,
seed?: T): Promise<T>;
export async function reduce<T>(
source: AsyncIterable<T>,
accumulator: (acc: T[], value: T, index: number) => T[],
seed?: T[]): Promise<T[]>;
export async function reduce<T, R>(
source: AsyncIterable<T>,
accumulator: (acc: R, value: T, index: number) => R,
seed?: R): Promise<R>;
export async function reduce<T, R>(
source: AsyncIterable<T>,
accumulator: (acc: T | R, value: T, index: number) => R,
...args: (T | R)[]): Promise<T | R> {
let [seed] = args;
const hasSeed = args.length === 1;
let i = 0, hasValue = false;
for await (let item of source) {
if (hasValue || (hasValue = hasSeed)) {
seed = accumulator(seed, item, i++);
} else {
seed = item;
hasValue = true;
i++;
}
}
if (!hasValue) {
throw new Error('Sequence contains no elements');
}
return seed!;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment