Packages@accelint/coreArray
reduce
Calls the accumulator with each element of the given array, starting with the first element, and returns the final accumulated result.
Usage
import { reduce } from '@accelint/core/array/reduce';
// Basic usage - sum numbers
const sum = reduce((total: number, n: number) => total + n)(0)([1, 2, 3, 4, 5]);
// 15
// Partial application
const sumNumbers = reduce((total: number, n: number) => total + n)(0);
sumNumbers([1, 2, 3]); // 6Reference
function reduce<T, R>(
fn: (accumulator: R, element: T) => R
): (initVal: R) => (arr: T[]) => RParameters
| Parameter | Type | Description |
|---|---|---|
fn | (accumulator: R, element: T) => R | Accumulator function called for each element. Receives the accumulator and current element, returns the new accumulator value. |
Returns
Returns a curried function that first accepts an initial value, then accepts an array, and finally returns the accumulated result.
Type Parameters
T- The type of array elementsR- The type of the accumulator and return value
Examples
Example: Building an object from array
import { reduce } from '@accelint/core/array/reduce';
interface User {
id: number;
name: string;
}
const users: User[] = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];
const userById = reduce(
(acc: Record<number, User>, user: User) => {
acc[user.id] = user;
return acc;
}
)({} as Record<number, User>)(users);
// { 1: { id: 1, name: 'Alice' }, 2: { id: 2, name: 'Bob' } }Example: Flattening arrays
import { reduce } from '@accelint/core/array/reduce';
const nested = [[1, 2], [3, 4], [5]];
const flat = reduce(
(acc: number[], arr: number[]) => acc.concat(arr)
)([])(nested);
// [1, 2, 3, 4, 5]Example: Counting occurrences
import { reduce } from '@accelint/core/array/reduce';
const words = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple'];
const counts = reduce(
(acc: Record<string, number>, word: string) => {
acc[word] = (acc[word] || 0) + 1;
return acc;
}
)({} as Record<string, number>)(words);
// { apple: 3, banana: 2, cherry: 1 }Example: Finding max value
import { reduce } from '@accelint/core/array/reduce';
const numbers = [5, 2, 9, 1, 7];
const max = reduce(
(acc: number, n: number) => Math.max(acc, n)
)(-Infinity)(numbers);
// 9Good to know: The accumulator function is called for every element in the array, left to right. The initial value is crucial—choose it carefully based on your accumulation logic. This is a pure function with no side effects.
Related
- map - Transform array elements
- filter - Filter array elements by predicate
- reduce-right - Reduce array from right to left