menu

manual-try-fold

Prefer Iterator.tryFold over reducing a propagated Result accumulator

Reducing a Result accumulator continues calling the reducer after failure only to propagate the same error again. Instead, you SHOULD call tryFold so iteration stops at the first failed Result.

The rule requires propagation to be the reducer's first operation, preserving every observable effect.

Reported

1import { Iterator } from "destack:iter";2 3function sum(values: Iterator<int32>): Result<int32, string> {4    return values.reduce((result, value) => {5        const total = result?;6 7        Result.ok(total + value)8    }, Result.ok(0));9}

Accepted

1import { Iterator } from "destack:iter";2 3function sum(values: Iterator<int32>): Result<int32, string> {4    return values.tryFold(0, (total, value) => Result.ok(total + value));5}