Created
May 4, 2017 19:44
-
-
Save mattpodwysocki/d1489932e0a8f52ac3f486e46eacf45f to your computer and use it in GitHub Desktop.
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
'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