For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /reference/array/unfold.md.

unfold

Builds an array from a seed value using an iterator function.

The iterator receives the current seed and returns either a [value, nextSeed] tuple to continue, or false to stop.

Dual of reduce — reduce collapses a list into a value, unfold expands a value into a list.

Termination is the caller's responsibility. If fn never returns false, unfold will run until memory is exhausted. For bounded generation, encode a counter or limit into the seed.

unfold((n) => (n > 0 ? [n, n - 1] : false), 5)
// [5, 4, 3, 2, 1]

Usage

unfold<T, R>(fn: (seed: T) => [R, T] | false, seed: T)

Builds an array from a seed value using an iterator function.

The iterator receives the current seed and returns either a [value, nextSeed] tuple to continue, or false to stop.

Dual of reduce — reduce collapses a list into a value, unfold expands a value into a list.

Termination is the caller's responsibility. If fn never returns false, unfold will run until memory is exhausted. For bounded generation, encode a counter or limit into the seed.

import { unfold } from 'massaman'
// or:  import { unfold } from 'massaman/array'

unfold((n) => (n > 0 ? [n, n - 1] : false), 5)
// [5, 4, 3, 2, 1]

Parameters

fn(seed: T) => [R, T] | falserequired

the function to apply.

seedTrequired

the initial seed value.

Returns

the generated values, ending when fn returns false.

R[]