@thi.ng/transducers-async
Version:
Async versions of various highly composable transducers, reducers and iterators
48 lines (47 loc) • 1.36 kB
JavaScript
import { NO_OP, SEMAPHORE } from "@thi.ng/api/api";
import { isAsyncIterable } from "@thi.ng/checks/is-async-iterable";
import { isIterable } from "@thi.ng/checks/is-iterable";
import { isReduced } from "@thi.ng/transducers/reduced";
import { ensureAsyncTransducer } from "./ensure.js";
import { push } from "./push.js";
async function* iterator1(xform, src) {
const [_, complete, reduce] = ensureAsyncTransducer(xform)([NO_OP, NO_OP, (_2, x) => x]);
for await (let x of src) {
let y = await reduce(SEMAPHORE, x);
if (isReduced(y)) {
const res = await complete(y.deref());
if (res !== SEMAPHORE) {
yield res;
}
return;
}
if (y !== SEMAPHORE) {
yield y;
}
}
}
async function* iterator(xform, src) {
const [_, complete, reduce] = ensureAsyncTransducer(
xform
)(push());
for await (let x of src) {
const y = await reduce([], x);
if (isReduced(y)) {
yield* await complete(y.deref());
return;
}
if (y.length) {
yield* y;
}
}
yield* await complete([]);
}
const __iter = (xform, args, impl = iterator1) => {
const n = args.length - 1;
return isIterable(args[n]) || isAsyncIterable(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
};