What is the recommended approach in JavaScript to passing around generators that include filtering + mapping logic?
Somehow, JavaScript generators are missing such fundamental things as filter
and map
operands, similar to arrays, to be able to create a generator that includes that logic, without having to run the iteration first.
My head-on approach was to implement custom functions that apply the logic:
function * filter(g, cb) {
let a;
do {
a = g.next();
if (!a.done && cb(a.value)) {
yield a.value;
}
} while (!a.done);
return a.value;
}
function * map(g, cb) {
let a;
do {
a = g.next();
if (!a.done) {
yield cb(a.value);
}
} while (!a.done);
return a.value;
}
But this creates a callback hell. I want to simply chain a generator, like a regular array:
// create a filtered & re-mapped generator, without running it:
const gen = myGenerator().filter(a => a > 0).map(b => ({value: b}));
// pass generator into a function that will run it:
processGenerator(gen);
Is there a way to extend generators to automatically have access to such basic functions?
As an extra, if somebody wants to weight in on why such fundamental things aren't part of the generators implementation, that'll be awesome! I would think that filtering and mapping are the two most essential things one needs for sequences.
UPDATE
This all ended with me writing my own iter-ops library :)