reduce
Module Export
[value] reduce (acc, item) => expression |> value | nothing[value] reduce default using (acc, item) => expression |> valueReduces an iterator to a single value using an accumulator function.
The reduce function folds an iterator into a single value by applying an accumulator function. It comes in two forms:
Without default value — The first item becomes the initial accumulator, and the function is called from the second item onward. If the iterator is empty, nothing is returned. This is sometimes called foldl1 in other functional languages.
With default value — Use the using keyword to provide an initial accumulator. The function is then called for every item, including the first. If the iterator is empty, the default value is returned.
Examples
Basic reduce
import 'iterators'
from [1, 2, 3] reduce (acc, item) => acc + itemResult:
6With default value
The using keyword separates the default value from the accumulator function:
import 'iterators'
from [1, 2, 3] reduce 0 using (acc, item) => acc + itemResult:
6Empty iterator without default
import 'iterators'
let numbers: [number] = []from numbers reduce (acc, item) => acc + itemResult:
nothingEmpty iterator with default
When a default is provided, it is returned for empty iterators:
import 'iterators'
let numbers: [number] = []from numbers reduce 99 using (acc, item) => acc + itemResult:
99Product
import 'iterators'
from [1, 2, 3, 4] reduce (acc, item) => acc * itemResult:
24Building a record from an iterator
import 'iterators'
from [{ key = 'a', value = 1 }, { key = 'b', value = 2 }] reduce {} using (acc, item) => acc with { '{item.key}' = item.value }Result:
{ a = 1, b = 2 }