reduce() function
foldl로도 알려진 이 메서드는 값 목록을 단일 값으로 축약합니다.
Signature:
typescript
declare function reduce<T extends readonly [], Acc>(
f: Arrow,
seed: Acc,
iterable: T,
): Acc;Example
You can reduce values into homogeneous type.
ts
const sum = (a: number, b: number) => a + b;
// with implicit seed with first element
reduce(sum, [1, 2, 3, 4]); // 10
// with explicit seed
reduce(sum, 0, [1, 2, 3, 4]); // 10You can reduce values into heterogeneous type.
ts
// reduce { id: number; score: number; } to number
reduce((acc, value) => acc + value.score, 0, [
{ id: 0, score: 1 },
{ id: 5, score: 2 },
{ id: 9, score: 3 },
{ id: 3, score: 4 },
]);Omitting iterable will returns function, useful when using with pipe.
ts
pipe(
[1, 2, 3, 4],
map((a) => a + 10),
filter((a) => a % 2 === 0),
reduce(sum),
); // 26For backward compatibility, reduce can support partial lazy form. You may want to use reduceLazy to use seed.
ts
await pipe(
Promise.resolve([1, 2, 3, 4]),
map((a) => a + 10),
filter((a) => a % 2 === 0),
reduce(sum),
); // 26
// if you want to use asynchronous callback
await pipe(
Promise.resolve([1, 2, 3, 4]),
toAsync,
map(async (a) => a + 10),
filter((a) => a % 2 === 0),
reduce(sum),
); // 26
// with toAsync
await pipe(
[
Promise.resolve(1),
Promise.resolve(2),
Promise.resolve(3),
Promise.resolve(4),
],
toAsync,
map((a) => a + 10),
filter((a) => a % 2 === 0),
reduce(sum),
); // 26