@thi.ng/transducers-async
Version:
Async versions of various highly composable transducers, reducers and iterators
48 lines (47 loc) • 1.11 kB
JavaScript
import { isNumber } from "@thi.ng/checks/is-number";
import { unreduced } from "@thi.ng/transducers/reduced";
import { __iter, iterator } from "./iterator.js";
function partition(...args) {
const iter = __iter(partition, args, iterator);
if (iter) return iter;
let size = args[0], all, step;
if (isNumber(args[1])) {
step = args[1];
all = args[2];
} else {
step = size;
all = args[1];
}
return ([init, complete, reduce]) => {
let buf = [];
let skip = 0;
return [
init,
async (acc) => {
if (all && buf.length > 0) {
acc = unreduced(await reduce(acc, buf));
buf = [];
}
return await complete(acc);
},
async (acc, x) => {
if (skip <= 0) {
if (buf.length < size) {
buf.push(x);
}
if (buf.length === size) {
acc = await reduce(acc, buf);
buf = step < size ? buf.slice(step) : [];
skip = step - size;
}
} else {
skip--;
}
return acc;
}
];
};
}
export {
partition
};