method Stream.fold
Stream.fold<U>(
fn: (
acc: U,
value: T,
) => Promisable<U>
,
initialValue: U,
): Promise<U>

Similar to Array.prototype.reduce, but works on the stream of results. If the provided function throws an error or returns a rejected promise, the error will be collected and emitted as an error result in the stream.

If any error results are present in the stream, they will be thrown as an AggregateError after the stream is exhausted. Use filterErr(() => false) upstream to explicitly drop errors if you want to fold only the successes.

Examples

Example 1

import { Stream } from "anabranch";

const stream = Source.from<number, string>(async function* () {
  yield 1;
  yield 2;
});

const sum = await stream.fold(async (acc, value) => {
  if (value === 2) {
    throw new Error("Value cannot be 2");
  }
  return acc + value;
}, 0);

console.log("Sum:", sum);

Type Parameters

Parameters

fn: (
acc: U,
value: T,
) => Promisable<U>
initialValue: U

Return Type

Promise<U>

Throws

AggregateError

If any error results were present in the stream.

See

Usage

import { type Stream } from ".";