JS: Iterator.prototype.flatMap
(new in ECMAScript 2025)
iterator.flatMap(f)-
- similar to Array.prototype.flatMap but works on Iterator.
- 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; } // if number is even, repeat it, else delete it const xx = gf().flatMap((x) => ((x % 2 === 0) ? [x, x] : [])); console.assert( JSON.stringify( Array.from(xx), ) === `[2,2,4,4,6,6]`, ); // is iterable console.assert( Reflect.has(xx, Symbol.iterator), ); // is iterator console.assert( Reflect.has(xx, "next"), );