Katxupa
  • 👋Welcome to Katxupa Extension Library
  • Why Katxupa?
    • 🍻What makes Katxupa special?
    • ✨Key Features
  • Get a taste of Katxupa
    • 🍲Installation
    • 🍜Usage
      • 🍻Scope Functions
        • Function Selection
        • Distinctions
        • Functions
          • letIt
          • withIt
          • runIt
          • applyIt
          • alsoIt
          • takeIf and takeUnless
      • 😎Null Safety
        • TypeScript Null-Safety
        • Optional Chaining for JavaScript
      • ⏰Duration
      • ➖Reducer
      • 📏Range
      • 🏃‍♂️Result
      • 🤼Either
      • 🟰Compare
      • ⚔️Global Utility Functions
    • 🤌Dip Dive
      • Optional
      • Range
      • Duration
      • Reducer
      • Collections
        • Array
        • Set
  • 🙏Support
    • Source Code
    • ESLint Config
    • TypeScript Docs
    • Manuel Santos Linkedin
Powered by GitBook
On this page
  • Examples:
  • Reducer with selector and implicit type comparator
  • Reducer with selector and custom comparator
  • Running reducer
  1. Get a taste of Katxupa
  2. Usage

Reducer

PreviousDurationNextRange

Last updated 1 year ago

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.

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))
🍜
➖
Reducer