Reducer

Array reduction is a fundamental operation in computer science and programming, allowing for the aggregation of elements within an array into a single value or a smaller array. It serves as a powerful tool for data processing, analysis, and transformation.

At its core, an array reducer operates on the principle of iteratively combining elements of an array according to a specified logic, often guided by user-defined functions or comparators. This process can involve summing numeric values, finding minimum or maximum elements, performing folds or scans, or applying custom reduction functions.

pageReducer

Examples:

Reducer with selector and implicit type comparator

const people = [
  { name: 'Alice', age: 30 },
  { name: 'Bob', age: 25 },
  { name: 'Charlie', age: 35 }
];
const reducer = reducerOf(people);
const minByAge = reducer.minBy((person) => person.age);
console.log(minByAge); 
// Output: { name: 'Bob', age: 25 }

Reducer with selector and custom comparator

const people = [
  { name: 'Alice', age: 30 },
  { name: 'Bob', age: 25 },
  { name: 'Charlie', age: 35 }
];
const minOfAge = reducerOf(people).minOfWith((person) => person.age, (a, b) => a - b);
console.log(minOfAge); 
// Output: { name: 'Bob', age: 25 }

Running reducer

const numbers = [1, 2, 3, 4, 5];
const reducer = (acc, num, index) => acc + (num + index);
const result = Reducer.of(numbers).runningReduceIndexed(reducer, 0);
console.log(result); 
// Output: [1, 4, 9, 16, 25] 
// -> (1, 1 + (2 + 1), (1 + (2 + 1)) + (3 + 2), ((1 + (2 + 1)) + (3 + 2)) + (4 + 3), (((1 + (2 + 1)) + (3 + 2)) + (4 + 3)) + (5 + 4))

Last updated