UNPKG

@thi.ng/transducers

Version:

Collection of ~170 lightweight, composable transducers, reducers, generators, iterators for functional data transformations

47 lines (46 loc) 1.21 kB
import { NO_OP, SEMAPHORE } from "@thi.ng/api/api"; import { isIterable } from "@thi.ng/checks/is-iterable"; import { ensureTransducer } from "./ensure.js"; import { push } from "./push.js"; import { isReduced, unreduced } from "./reduced.js"; function* iterator(xform, src) { const rfn = ensureTransducer(xform)(push()); const complete = rfn[1]; const reduce = rfn[2]; for (let x of src) { const y = reduce([], x); if (isReduced(y)) { yield* unreduced(complete(y.deref())); return; } if (y.length) { yield* y; } } yield* unreduced(complete([])); } function* iterator1(xform, src) { const reduce = ensureTransducer(xform)([NO_OP, NO_OP, (_, x) => x])[2]; for (let x of src) { let y = reduce(SEMAPHORE, x); if (isReduced(y)) { y = unreduced(y.deref()); if (y !== SEMAPHORE) { yield y; } return; } if (y !== SEMAPHORE) { yield y; } } } const __iter = (xform, args, impl = iterator1) => { const n = args.length - 1; return isIterable(args[n]) ? args.length > 1 ? impl(xform.apply(null, args.slice(0, n)), args[n]) : impl(xform(), args[0]) : void 0; }; export { __iter, iterator, iterator1 };