DEV Community

Kaziu
Kaziu

Posted on

🌀 Iterator and Generator

💎 Iterator

iterator is function which has next function which returns object {done, value}

function genIterator(num) {
  return {
    next: function() { // ⭐ next!!
      return {
        done: true / false, // ⭐ done!!
        value: some value // ⭐ value!!
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

For example??

function genIterator(num) {
  let i = 0

  return {
    next: function() {
      return {
        done: false,
        value: i
      }
    }
  }
}

const it = genIterator()
Enter fullscreen mode Exit fullscreen mode

↓ How to use it ??

console.log(it.next()) // 0
console.log(it.next()) // 1
console.log(it.next()) // 2
console.log(it.next()) // 3
Enter fullscreen mode Exit fullscreen mode

(By the way this is used basic style of closure)

↓ How to set max value?

function genIterator(num) {
  let i = 0

  return {
    next: function() {
      if(i >= num) {
        return {
          done: true// ⭐ here!!
        }
      } else {
        return {
          done: false,
          value: i
        }
      }
    }
  }
}

const it = genIterator(10)

let one = it.next()
while(!one.done) {
  console.log(one.value)
  one = it.next()
}
// 0 1 2 3 4 5 6 7 8 9
Enter fullscreen mode Exit fullscreen mode

💎 Generator

generator is function to create iterator

Actually it's just simple version of iterator 🤗🤗

function* generator() { //⭐ asterisk !!
  if(loop continue) {
    yield value; //⭐ keyword "yield" 
  } else {
    return value;
  }
}
Enter fullscreen mode Exit fullscreen mode

function* ← 🤔 what is this asterisk??
😎 it defines this function is GENERATOR !!!

yield ← 🤔 what is this??
😎 it returns {value, done}, like iterator

▼ Let's make simple example

function* generator() {
  yield 1
  yield 2
  return 3
}

const it = generator()
// ⭐ return {value, done} like iterator !!
console.log(it.next()) // {value: 1, done: false}
console.log(it.next()) // {value: 2, done: false}
console.log(it.next()) // {value: 3, done: true}
console.log(it.next()) // {value: undefined, done: true}
Enter fullscreen mode Exit fullscreen mode

▼ Let's transform counter function (genIterator function) by generator

function* genIterator(num = 10) {
  let i = 0
  while(i < num) {
    yield i++
  }
}

const it = genIterator(10)

let one = it.next()// ⭐ execute by next() like itarator !!!
while(!one.done) {
  console.log(one.value)
  one = it.next()
}
// 0 1 2 3 4 5 6 7 8 9
Enter fullscreen mode Exit fullscreen mode

Generators are also iterable

function* alphabets() {
  yield 'a'
  yield 'b'
  yield 'c'
}

for(let letter of alphabets()) {
  console.log(letter)
}

// a b c
Enter fullscreen mode Exit fullscreen mode

Top comments (0)