Day 47 of #100DaysOfCode:Review ES6 Generators & Iterators

jenhsuan

Jen-Hsuan Hsieh

Posted on November 17, 2020

Day 47 of #100DaysOfCode:Review ES6 Generators & Iterators

Introduction

Generators is a new feature from ES6 which can help us to maintain the internal state (pause and resume)

The Iterator Protocol

  • The iterator protocol means a process for defining how an object will iterate.This is done through implementing the .next() method.
const list = [0, 1, 2, 3, 4, 5];
const arrayIterator = list[Symbol.iterator]();

console.log(arrayIterator.next());
console.log(arrayIterator.next());
console.log(arrayIterator.next());
/*
will print:
Object {value: 0, done: false}
Object {value: 1, done: false}
Object {value: 2, done: false}
*/
Enter fullscreen mode Exit fullscreen mode
  • value: represent the next value in the sequence
  • done: represent if the iterator is done ging through the sequence

Pausable Functions

  • When a generator is invoked, it doesn't actually run any of the code inside the function. Instead, it creates and returns an iterator.
  • The function will be transformed to a pausable function if we put asterisk after the function keyword.
  • yield is the keyword that causes the generator to pause
  • The state machine(Generators) will transform the state: initial state -> resume -> pause (state 1) -> resume -> pause (state 2) -> resume -> .... -> end (state N)

Alt Text

Sending data into/out of a Generator

  • yield is used to send data outside the generator
  • .next() method is used to send data inside the generator
function* gen3() {
    for (let i = 0; i< 10; i++) {
        let value = yield i
        console.log(`sending data into generator: ${value}`)
    }
}


var g = gen3()
console.log(`sending data out of generator: ${g.next().value}`)
console.log(`sending data out of generator: ${g.next(10).value}`)
console.log(`sending data out of generator: ${g.next(20).value}`)
/*
will print:
sending data out of generator: 0
sending data into generator: 10
sending data out of generator: 1
sending data into generator: 20
sending data out of generator: 2
*/
Enter fullscreen mode Exit fullscreen mode

Articles

There are some of my articles and released projects. Feel free to check if you like!

References

💖 💪 🙅 🚩
jenhsuan
Jen-Hsuan Hsieh

Posted on November 17, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related