Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

What are JavaScript Generators? #1

Open
mharoot opened this issue Apr 18, 2019 · 1 comment
Open

What are JavaScript Generators? #1

mharoot opened this issue Apr 18, 2019 · 1 comment
Assignees
Labels

Comments

@mharoot
Copy link
Owner

mharoot commented Apr 18, 2019

source

https://codeburst.io/what-are-javascript-generators-and-how-to-use-them-c6f2713fd12e

(function start(){

  function makeRangeIterator(start = 0, end = Infinity, step = 1) {
      let nextIndex = start;
      let iterationCount = 0;

      const rangeIterator = {
         next: function() {
             let result;
             if (nextIndex < end) {
                 result = { value: nextIndex, done: false }
                 nextIndex += step;
                 iterationCount++;
                 return result;
             }
             return { value: iterationCount, done: true }
         }
      };
      return rangeIterator;
  }
  function runMakeRangeIteratorTest() {
    let it = makeRangeIterator(1, 10, 2);

    let result = it.next();
    while (!result.done) {
     console.log(result.value); // 1 3 5 7 9
     result = it.next();
    }

    console.log("Iterated over sequence of size: ", result.value); // 5
  }
  
function * generatorForLoop(num) {
  for (let i = 0; i < num; i += 1) {
    yield console.log(i);
  }
}

const genForLoop = generatorForLoop(5);

genForLoop.next(); // first console.log - 0
genForLoop.next(); // 1
genForLoop.next(); // 2
genForLoop.next(); // 3
genForLoop.next(); // 4

})();
@mharoot mharoot self-assigned this Apr 18, 2019
@mharoot
Copy link
Owner Author

mharoot commented Apr 19, 2019

Prime Number Generator

(function start(){
  function isPrime(num) {
    for ( var i = 2; i < num; i++ ) {
      if ( num % i === 0 ) {
        return false;
      }
    }
    return true;
  }
  function* primeNumGenerator( start = 2, stop = 100 ) {
    for ( var i = start; i < stop; i++) {
      if ( isPrime(i) ) yield i;
      else continue;
    }
  }

  let it = primeNumGenerator(2, 100);
  alert( it.next().value );
  alert( it.next().value );
  alert( it.next().value );
  alert( it.next().value );
})();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant