@push-stream-std/push-unfold (0.0.5)
Installation
@push-stream-std:registry=https://hub.kl1.tenere.ai/api/packages/push-stream-std/npm/npm install @push-stream-std/push-unfold@0.0.5"@push-stream-std/push-unfold": "0.0.5"About this package
push-unfold
Generate a push-stream source by repeated function application from a seed value.
Published as @push-stream-std/push-unfold.
Synopsis
import unfold from '@push-stream-std/push-unfold';
// Synchronous: unfolder receives current seed, returns { value, seed } or null to end
const naturals = unfold((n) => {
if (n > 5) return null;
return { value: n, seed: n + 1 };
}, 1);
const sink = {
paused: false,
write(v) { console.log(v); },
end() { console.log('done'); }
};
naturals.pipe(sink);
// Output: 1, 2, 3, 4, 5, done
// Asynchronous: unfolder receives (seed, callback)
const delayed = unfold((n, cb) => {
if (n > 3) return cb(null, null);
setTimeout(() => cb(null, { value: n, seed: n + 1 }), 100);
}, 1);
delayed.pipe(sink);
// Output: 1, 2, 3, done
Install
npm config set @push-stream-std:registry https://hub.kl1.tenere.ai/api/packages/push-stream-std/npm/
npm config set -- //hub.kl1.tenere.ai/api/packages/push-stream-std/npm/:_authToken "$PACKAGE_TOKEN"
npm install @push-stream-std/push-unfold
Description
A push-stream source that lazily generates a sequence by applying an "unfolder" function to a seed value. Each call returns either a { value, seed } object (to emit a value and update the seed) or null/undefined to end the stream. The async form (detected when unfolder.length === 2) accepts a callback (err, result) for callback-based asynchronous generation. Sync unfolder errors and async errors are propagated to the sink via end(err).
API
unfold(unfolder, seed)
Creates an unfold source stream.
- unfolder
Function– A function that receives the current seed and either returns a result synchronously or (ifunfolder.length === 2) calls a callback(err, result). The result must be either:{ value: any, seed: any }– Emitvalueand continue with the newseed.nullorundefined– End the stream.
- seed
any– The initial seed value. - Returns A source stream with
pipe(),resume(),end(),abort(),paused, andended.
Tests
npm test
Tests cover sync generation from seed, sync termination via null return, sync error propagation, async generation via callback, async termination, and async error propagation.
Requirements
Node.js 18 or later. ESM only.
License
MIT