JavaScript, inside out · Chapter 32 of 51
Iterators and generators
By the end of this chapter you can write your own iterators and generators: values made one at a time, only when someone asks, even from a list that never ends. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Modern JavaScript
- 5 tasks
- JavaScript
- In the all labs plan
The first 2 chapters of JavaScript, inside out are free. This one comes with the all labs plan.
Why you need this
During the 4 pm rush the kitchen screen builds an array of the next thousand token numbers "just in case", then uses three of them, and the old tablet by the stove stutters. Ravi asks: "Can it make the next number only when someone asks for it?" Anjali wants the menu screen to walk the items in stock without building a list first, and Kabir wants the brewing steps one at a time, with a last message at the end.
With what you know so far, every list is an array, made in full before anyone reads it (in chapter 31 you borrowed an array's iterator, but there still had to be an array). "Every token from now on" cannot be an array at all: spreading an endless list runs until Node gives up:
FATAL ERROR: invalid array length Allocation failed - JavaScript heap out of memoryWhat you build: 5 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
makeTokenRange: a token range written by hand
Write makeTokenRange(from, to) with the iterator protocol, by hand (no generator needed). Return an iterable object: its Symbol.iterator method returns an iterator whose next() gives { value, done: false } for every token number from from to to, both included, in order, and then { value: undefined, done: true } on that call and every call after it.
[...makeTokenRange(5, 8)] gives [5, 6, 7, 8], and spreading the same range a second time gives [5, 6, 7, 8] again. A range with from greater than to gives [], and makeTokenRange(1, 1) gives [1].
- Task 2
availableItems: a generator of the items in stock
Write availableItems(menu) as a generator function. It yields the name of every menu item whose stock is above 0, in menu order, and skips the items with stock 0. Calling it must return a generator object: it has next(), and it is its own iterator.
For a menu of Masala chai (stock 120), Bun maska (0), Cutting chai (40) and Parle-G (6), it yields 'Masala chai', 'Cutting chai' and 'Parle-G'. An empty menu yields nothing.
- Task 3
tokenNumbers and take: endless tokens, only as many as needed
Write tokenNumbers(start) as a generator that never ends: it yields start, start + 1, start + 2 and so on, forever.
Write take(iterable, n). It returns an array of the first n values of any iterable (a generator or an array), and pulls no more than n values from it: take(tokenNumbers(100), 3) gives [100, 101, 102], and a generator that counts its pulls has been pulled exactly 4 times after taking 4. With n of 0 it returns [] without pulling anything. An iterable shorter than n gives all of its values: take(['a', 'b'], 5) gives ['a', 'b'].
- Task 4
brewSteps and collect: the steps and the final message
Write brewSteps() as a generator that yields 'boil water', 'add tea leaves' and 'add milk and sugar', in that order, and then returns 'chai is ready'. Spreading it gives only the three steps.
Write collect(iterator). Call next() until done is true and return an object with two keys: values (every yielded value, in order) and returned (the value of the last step, the one with done true). collect(brewSteps()) gives { values: ['boil water', 'add tea leaves', 'add milk and sugar'], returned: 'chai is ready' }. A generator that yields 'x' and returns nothing gives { values: ['x'], returned: undefined }.
- Task 5 · interview question
Interview: prediction, spreading the same generator twice
Export prediction, an object with two keys, first and second: the arrays that first and second hold after the snippet in the comment above it runs. Write each one as a real array of strings, such as ['a', 'b'], or [] for an empty array.
The check runs the same snippet and compares.
What you will learn
- The iterator protocol: an object whose next() hands out { value, done }, written by hand.
- Generators: function* and yield, which write that object for you and pause between values.
- Lazy, endless sequences: values made only when pulled, and a loop that stops pulling with break.
- The return value: the last message a generator hands over with done: true.
More in Modern JavaScript
Build "Iterators and generators" yourself
Tapri, a chai brand going online, needs its menu, orders and kitchen in code. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of JavaScript, inside out are free. This one comes with the all labs plan.