Skip to content

Commit 3100257

Browse files
committed
✨ Reduce
1 parent aec546b commit 3100257

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

src/language/for_each.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
export type ForEachCallback<T> = (
2+
element: T,
3+
index: number,
4+
array: readonly T[],
5+
) => void;
6+
7+
export function forEach<T>(array: T[], callback: ForEachCallback<T>) {
8+
const entries = array.entries();
9+
10+
for (const [index, value] of entries) {
11+
callback(value, index, array);
12+
}
13+
}

src/language/reduce.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
export type ReduceCallback<T> = (
2+
accumulator: T,
3+
value: T,
4+
index: number,
5+
array: readonly T[],
6+
) => unknown;
7+
8+
export function reduce<T, F extends ReduceCallback<T>>(
9+
array: T[],
10+
callback: F,
11+
initialValue?: unknown,
12+
) {
13+
const copy = [...array];
14+
15+
if (array.length >= 1) {
16+
initialValue = copy.shift();
17+
}
18+
19+
let previous = initialValue;
20+
21+
const entries = copy.entries();
22+
23+
for (const [index, element] of entries) {
24+
previous = callback(previous as T, element, index, array);
25+
}
26+
27+
return previous as ReturnType<F>;
28+
}

0 commit comments

Comments
 (0)