1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import type { MaybePromise } from "https://esm.town/v/postpostscript/typeUtils";
// reference: https://github.com/microsoft/TypeScript/blob/main/src/lib/es5.d.ts#L1272
export type AsyncReducer<U, T> =
| ((acc: T, next: T, index: number, values: T[]) => MaybePromise<T>)
| ((acc: T, next: T, index: number, values: T[]) => MaybePromise<T>)
| ((acc: U, next: T, index: number, values: T[]) => MaybePromise<U>);
export async function reduceAsync<U, T>(
values: T[],
reducer: (acc: T, next: T, index: number, values: T[]) => MaybePromise<T>,
): Promise<T>;
export async function reduceAsync<U, T>(
values: T[],
reducer: (acc: T, next: T, index: number, values: T[]) => MaybePromise<T>,
initialValue: T,
): Promise<T>;
export async function reduceAsync<U, T>(
values: T[],
reducer: (acc: U, next: T, index: number, values: T[]) => MaybePromise<U>,
initialValue: U,
): Promise<U>;
export async function reduceAsync<U, T>(
values: T[],
reducer: AsyncReducer<U, T>,
initial?: T | U,
) {
const hasInitial = arguments.length > 2 ? 1 : 0;
if (!hasInitial && !values.length) {
throw new Error("reduceAsync needs at least one values element or an initial value");
}
const acc = hasInitial ? initial : values[0];
let accPromise = acc instanceof Promise
? acc
: (async () => acc)();
let i = hasInitial ? 0 : 1;
for (i = 0; i < values.length; i++) {
const index = i;
accPromise = accPromise.then(acc => reducer(acc, values[index], index, values));
}
return accPromise;
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
February 28, 2024