-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
reduce.ts
84 lines (82 loc) · 2.25 KB
/
reduce.ts
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/**
* Reduces an iterable into a single value.
*
* The first value of the iterable is used as the initial value.
*
* Use {@linkcode https://jsr.io/@core/iterutil/doc/map/~/map map} to transform values of the iterable.
* Use {@linkcode https://jsr.io/@core/iterutil/doc/filter/~/filter filter} to filter values of the iterable.
* Use {@linkcode https://jsr.io/@core/iterutil/doc/async/reduce/~/reduce reduce} to reduce an iterable asynchronously.
*
* @param iterable The iterable to reduce.
* @param fn The function to reduce with.
* @returns The reduced value.
*
* @example
* ```ts
* import { reduce } from "@core/iterutil/reduce";
*
* const result = reduce(
* [1, 2, 3, 4, 5],
* (a, v) => a + v,
* );
* console.log(result); // 15
* ```
*/
export function reduce<T>(
iter: Iterable<T>,
fn: (acc: T, value: T, index: number) => T,
): T | undefined;
/**
* Reduces an iterable into a single value.
*
* Use {@linkcode https://jsr.io/@core/iterutil/doc/map/~/map map} to transform values of the iterable.
* Use {@linkcode https://jsr.io/@core/iterutil/doc/filter/~/filter filter} to filter values of the iterable.
* Use {@linkcode https://jsr.io/@core/iterutil/doc/async/reduce/~/reduce reduce} to reduce an iterable asynchronously.
*
* @param iterable The iterable to reduce.
* @param fn The function to reduce with.
* @param initial The initial value to start reducing with.
* @returns The reduced value.
*
* @example
* ```ts
* import { reduce } from "@core/iterutil/reduce";
*
* const result = reduce(
* [1, 2, 3, 4, 5],
* (a, v) => a + v,
* "",
* );
* console.log(result); // 12345
* ```
*/
export function reduce<T, U>(
iter: Iterable<T>,
fn: (acc: U, value: T, index: number) => U,
initial: U,
): U;
export function reduce<T, U = T>(
iterable: Iterable<T>,
fn: (acc: U, value: T, index: number) => U,
initial?: U,
): U | undefined {
const it = iterable[Symbol.iterator]();
let index = 0;
if (initial == null) {
const { done, value } = it.next();
if (done) {
return undefined;
}
initial = value as unknown as U;
index = 1;
}
let acc: U = initial;
while (true) {
const { done, value } = it.next();
if (done) {
break;
}
acc = fn(acc, value as T, index++);
}
return acc;
}