DEV Community

Cover image for Implementing your own Generator using closure !!!
sakethk
sakethk

Posted on • Edited on

Implementing your own Generator using closure !!!

Here is a small program generating x to y numbers using generator in JS later we will implement equivalent function by using closure.


Generating x to y numbers using Generator


function *genXtoY(x, y){
  while(x < y)
    yield x++
  return x++      
}

const _iter = genXtoY(1, 5)

_iter.next() //{ value: 1, done: false }
_iter.next() //{ value: 2, done: false }
_iter.next() //{ value: 3, done: false }
_iter.next() //{ value: 4, done: false }
_iter.next() //{ value: 5, done: true }
_iter.next() //{ value: undefined, done: true }

Enter fullscreen mode Exit fullscreen mode

Generating x to y numbers using closure


const genXtoY = (x, y) => {
  const next = () => {
    if(x <= y)
      return {value: x++, done: (x - 1 === y)}

    return {value: undefined, done: true}
  }
  return {next}
}

const _iter = genXtoY(1, 5)

_iter.next() //{ value: 1, done: false }
_iter.next() //{ value: 2, done: false }
_iter.next() //{ value: 3, done: false }
_iter.next() //{ value: 4, done: false }
_iter.next() //{ value: 5, done: true }
_iter.next() //{ value: undefined, done: true }

Enter fullscreen mode Exit fullscreen mode

Top comments (0)