Give me the next order

Published 4 months ago

In JavaScript an iterator is an object which defines a sequence and potentially a return value upon its termination.

Once created, an iterator object can be iterated by repeatedly calling next(). We can only consume the iterator once. After the final value has been yielded, additional calls to next() should return { done: true }.

Lets build a simple, custom iterator.

function createFlow(arr) {
  let index = 0;

  return {
    next() {
      const value = arr[index];
      index++;
      return index <= arr.length ? { value, done: false } : { done: true };
    },
  };
}

Here we are using the iterator protocol. This protocol defines a standard method to produce a sequence of values and a return value once all the values have been generated.

The next method always has to return an object with appropriate properties including done and value.

const orders = ["prawns", "cheeseburger", "ice cream"];

const nextOrderPlease = createFlow(orders);

We have declared a set of orders and initialised our custom iterator, passing it our orders array.

Now lets try out this next() method...

nextOrderPlease.next(); // { value: 'prawns', done: false }
nextOrderPlease.next(); // { value: 'cheeseburger', done: false }
nextOrderPlease.next(); // { value: 'ice cream', done: false }
nextOrderPlease.next(); // { done: true }

This is a pretty cool way of iterating over a stream of data with an unknown length. But wait until you see what generators can do...