DEV Community

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

Posted on • Edited on

2

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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs