Iterables

Iterable Values

Where Iterable Values Are Used

What Values are Iterable

Iterators

Implementing an Iterable

Example: Range

class Range {
  constructor(from, to) {
    this.from = from
    this.to = to
  }
  [Symbol.iterator]() {
    let current = this.from
    return {
      next: () => {
        if (current < this.to) {
          const result = { value: current }
          current++
          return result
        }
        else
          return { done: true }
      }
    }
  }
}

Closeable Iterators

Closeable Iterator Implementation

function lines(filename) {
  const file = ... // Open the file
  return {
    [Symbol.iterator]: () => ({
      next: () => {
        if (done) {
          ... // Close the file
          return { done: true }
        }
        else {
          const line = ... // Read a line
          return { value: line }
        }
      },
    ['return']: () => {
        ... // Close the file
        return { done: true } // Must return an object
      }
    })
  }
}

Generators

Generators

Generator Function Syntax

Execution Flow

Nested Yield

Nested Yield

Generators as Consumers

End of Lesson 9