Finding Your itertools in JavaScript

Priya’s previews now run on iterator helpers. A counter() generator stands in for count(), and .drop() with .take() does the work of islice(), except that .take() closes its source when it finishes. Her Python service reaches for more of itertools than that, though. It joins batches of sample numbers with chain(), selects the cool morning readings with takewhile(), and keeps running totals with accumulate().

JavaScript has no itertools module, so each of those calls needs a new home before the port can stay lazy. In this lesson, you’ll find that home for each tool. Some are built-in helpers, some are short function* generators, and a few have no direct counterpart at all.

Join Iterators With the Built-In Helpers

The station sends sample numbers in batches, and the service either joins two batches or flattens a list of them. In Python, both are forms of chain():

Language: Python
from itertools import chain

print(list(chain([1], [2, 3])))
print(list(chain.from_iterable([[1], [2, 3]])))

Both lines print [1, 2, 3]. In the JavaScript port, Iterator.concat() takes the place of chain(), and the iterator’s .flatMap() takes the place of chain.from_iterable():

Language: JavaScript
const joined = Iterator.concat([1], [2, 3]).toArray();
console.log(joined);

const batches = [[1], [2, 3]];
const flat = Iterator.from(batches)
  .flatMap((batch) => batch)
  .toArray();
console.log(flat);

Both give the same three sample numbers:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.