Skip to main content
Deno 2 is finally here 🎉️
Learn more
Module

x/iter/lib/reducers.ts>reduce

A bunch of utilities for working with iterables, many inspired by the native array methods.
Latest
function reduce
import { reduce } from "https://deno.land/x/iter@v3.2.3/lib/reducers.ts";

Calls the specified callback function for all the items in an iterable. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

Examples

Example 1

import * as iter from "https://deno.land/x/iter";

const naturals = iter.create.increments(1);
// The first triangular number which is a multiple of 13
const luckyNumber = iter.reduce(
  naturals,
  (tot, n) => tot + n,
  0,
  (tot) => tot % 13 === 0,
);

console.log(luckyNumber); // -> 78

Parameters

it: Iterable<T>

The iterable to be reduced.

A function that accepts up to four arguments. The reduce function calls f one time for each item in the iterable, unless it is stopped early.

initialValue: U

If initialValue is specified, it is used as the initial value to start accumulation. The first call to f provides this value as an argument.

optional
stop: ReduceStopCallback<T, U> = [UNSUPPORTED]

A functin similar to f. If it returns false, reduce will stop early and return the current accumulated value.

Returns

The final accumulator value.