Skip to content

Latest commit

 

History

History
86 lines (54 loc) · 2.08 KB

reducers.md

File metadata and controls

86 lines (54 loc) · 2.08 KB

Reducers

Methods to convert an iterable to a single value of some sort.

Usage

import { generators, reducers } from 'iterablefu'
console.log(reducers.toArray(generators.range(5))) // prints [0, 1, 2, 3, 4]

Table of Contents

forEach

Executes function fn(item, index) for each item in the iterable sequence provided.

Parameters

  • fn Function a function(item, index), where item is the current item in the sequence, and index is the index of the current item.
  • iterable Iterable the sequence of items to call fn(item, index) with.

Examples

const fn = (item, index) => console.log(`item - ${item}, index - ${index}`)
forEach(fn, [1, 2, 3]) // prints the following...
// item - 1, index - 0
// item - 2, index - 1
// item - 3, index - 2

Returns undefined

reduce

The reduce() method executes a reducer function on each element of the input iterable, resulting in a single output value.

Parameters

  • fn Function fn(accumulator, item) that returns the new accumulator value
  • accumulator any the initial accumulator value
  • iterable Iterable the sequence to execute fn over.

Examples

const add = (a, b) => a + b
const sum = reduce(add, 0, [0, 1, 2, 3, 4]) // sum === 10

Returns any the final accumulator value

toArray

Creates an Array from the items in iterable.

Parameters

  • iterable Iterable the iterable to create the array from

Examples

const a = toArray(range(5)) // a is [0, 1, 2, 3, 4]

Returns Array the array