JS: Iterator.prototype.flatMap
(new in ECMAScript 2025)
iterator.flatMap(f)-
- similar to Array.prototype.flatMap but works on Iterator Object.
- Return a new Generator.
f is passed args: currentElement, currentIndex.
// define a generator function function* gf() { for (let x of [1, 2, 3, 4, 5, 6]) yield x; } // create a generator. a generator is both iterable and iterator const xgen = gf(); // if number is even, repeat it, else delete it const xresult = xgen.flatMap((x) => ((x % 2 === 0) ? [x, x] : [])); console.assert( JSON.stringify( Array.from(xresult), ) === `[2,2,4,4,6,6]`, ); // result is iterable console.assert( Reflect.has(xresult, Symbol.iterator), ); // result is iterator console.assert( Reflect.has(xresult, "next"), );