@thi.ng/transducers
Version:
Collection of ~170 lightweight, composable transducers, reducers, generators, iterators for functional data transformations
28 lines (27 loc) • 723 B
JavaScript
import { isIterable } from "@thi.ng/checks/is-iterable";
import { isString } from "@thi.ng/checks/is-string";
import { compR } from "./compr.js";
import { iterator } from "./iterator.js";
import { isReduced } from "./reduced.js";
function flattenWith(fn, src) {
return isIterable(src) ? iterator(flattenWith(fn), isString(src) ? [src] : src) : (rfn) => {
const reduce = rfn[2];
const flatten = (acc, x) => {
const xx = fn(x);
if (xx) {
for (const y of xx) {
acc = flatten(acc, y);
if (isReduced(acc)) {
break;
}
}
return acc;
}
return reduce(acc, x);
};
return compR(rfn, flatten);
};
}
export {
flattenWith
};