@thi.ng/transducers
Version:
Collection of ~170 lightweight, composable transducers, reducers, generators, iterators for functional data transformations
32 lines (31 loc) • 757 B
JavaScript
import { __iter, iterator } from "./iterator.js";
import { isReduced } from "./reduced.js";
function partitionWhen(...args) {
return __iter(partitionWhen, args, iterator) || (([init, complete, reduce]) => {
const pred = args[0];
const f = args[1] === true ? pred() : pred;
let chunk;
return [
init,
(acc) => {
if (chunk?.length) {
acc = reduce(acc, chunk);
chunk = null;
}
return complete(acc);
},
(acc, x) => {
if (f(x)) {
chunk && (acc = reduce(acc, chunk));
chunk = isReduced(acc) ? null : [x];
} else {
chunk ? chunk.push(x) : chunk = [x];
}
return acc;
}
];
});
}
export {
partitionWhen
};