brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: iterator helpers like filter() and take() work on generators without making an array

Javascript
~/tips/tip-js-iterator-helpers-take

function* naturals() {

Map, filter and limit any iterator lazily, even an endless one.

Array methods only work on arrays, so with a generator or a Map I’d spread it into an array first. Iterators now have map, filter, take and friends of their own.

function* naturals() {
  let i = 1;
  while (true) yield i++;
}

naturals()
  .filter((n) => n % 3 === 0)
  .map((n) => n * n)
  .take(4)
  .toArray(); // [9, 36, 81, 144]

const tags = new Map([["css", 12], ["git", 30]]);
tags.keys().map((k) => k.toUpperCase()).toArray(); // ["CSS", "GIT"]

The helpers are lazy. Nothing runs until toArray() asks for values, and then each number flows through the chain one at a time. That is why the endless generator is fine: take(4) stops it after four results. With arrays you would need the whole list in memory first.

Besides these there are drop, flatMap, reduce, some, every, find and forEach. For an iterable that is not a real iterator, Iterator.from() wraps it.

A difference that can bite: a helper chain can only be consumed once. Call toArray() twice on the same chain and the second call returns an empty array, because the iterator is used up.

Support: Chrome 122, Firefox 131, Safari 18.4 and Node.js 22.

Further reading: MDN: Iterator, MDN: Iterator.prototype.take()

More Javascript tips node --inspect-brk app.js obj?.prop const filePath = String.raw`C:\Development\profile\about.html`; const observer = new ResizeObserver((entries) => { URL.parse("not a url"); // null All Javascript tips (40) All topics

Link