sg

sane-generator

ECMAScript 6 Generator which doesn't die when the loop iterating it breaks

Showing:

Popularity

Downloads/wk

3

GitHub Stars

3

Maintenance

Last Commit

5yrs ago

Contributors

3

Package

Dependencies

0

Size (min+gzip)

0.2KB

License

GPL-3.0

Type Definitions

Tree-Shakeable

No?

Categories

Readme

sane-generator

npm version Build Status Coverage Status


Why do I need Sane Generator?

In short, ECMAScript 6 Generators are closed if we break out of the loop which iterates them. I believe that this limits the Generators. For example, in Python, the following would work

>>> numbers = (num for num in range(10))
>>> for num in numbers:
...   if num == 3:
...     break
...
>>> next(numbers)
4

This allows us partially consume the Generators whenever we want and that allows us to have elegant solutions like this one, by Jon Clements.

But the similar code in ECMAScript 6 would close the generator.

function* NumberGenerator() {
  for (var i = 0; i < 10; i += 1) {
    yield i;
  }
}

var numbers = NumberGenerator();

for (var num of numbers) {
  if (num === 3) {
    break;
  }
}

console.log(numbers.next());
// {"done": true}

This module provides a way to overcome this feature.

I explained in detail in this blog post http://www.thefourtheye.in/2016/02/sane-ecmascript-6-generators.html.

Installation

npm install sane-generator

Usage

var SaneGenerator = require('sane-generator');

function* NumberGenerator() {
  for (var i = 0; i < 10; i += 1) {
    yield i;
  }
}

var numbers = SaneGenerator(NumberGenerator());

for (var num of numbers) {
  if (num === 3) {
    break;
  }
}

console.log(numbers.next());
// {"value": 4, "done": false}

How to explicitly close the SaneGenerator?

var SaneGenerator = require('sane-generator');

function* NumberGenerator() {
  for (var i = 0; i < 10; i += 1) {
    yield i;
  }
}

var numbers = SaneGenerator(NumberGenerator());

console.log(numbers.next());
// {"value": 0, "done": false}
console.log(numbers.next());
// {"value": 1, "done": false}
console.log(numbers.return(undefined));              // call `return` with any value
// {"done": true}
console.log(numbers.next());
// {"value": undefined, "done": true}

Rate & Review

Great Documentation0
Easy to Use0
Performant0
Highly Customizable0
Bleeding Edge0
Responsive Maintainers0
Poor Documentation0
Hard to Use0
Slow0
Buggy0
Abandoned0
Unwelcoming Community0
100