Skip to content

.tip

· one of the small things

Iterator helpers stop you building arrays you throw away

lines.map(parse).filter(isError).slice(0, 10) parses every line and allocates two arrays to keep ten. Iterator helpers are lazy: each value is pulled through the chain one at a time, and the work stops once the consumer has enough.

const firstErrors = lines
  .values()
  .map(parse)
  .filter((e) => e.level === "error")
  .take(10)
  .toArray();

take ends the pull, so parse runs only until the tenth error. drop, flatMap and reduce are there too, on anything with an iterator, Map.entries() included. Node 22 and current browsers.

javascript