MarkoCen / markocen.com

Personal website
http://www.markocen.com
1 stars 0 forks source link

JavaScript: Make an Iterable Class #15

Open MarkoCen opened 2 years ago

MarkoCen commented 2 years ago

In JavaScript, we can iterate an iterable object using the built-in for ... of syntax. We can make a class iterable by implementing the iterable protocol. To implement the protocol, the class must have a property with a @@iterator key which is available via constant Symbol.iterator

class Items {
  constructor(height, width) {
    this.list = [1, 2, 3, 4, 5];
  }

  // the protocol interface should return an object with a next method
  [Symbol.iterator]() {
    // Use a new index for each iterator. This makes multiple
    // iterations over the iterable safe for non-trivial cases,
    // such as use of break or nested looping over the same iterable.
    let index = 0;

    return {
      next: () => {
        const value = this.list[index];
        const done = index >= this.list.length - 1;
        index++;
        return { value, done }
      }
    }
  }
}

Then we can iterate over this class like we did with a built-it iterable object (array, may, etc.)

const items = new Items();

for (const item of items) {
   console.log(item);
}