zero-to-mastery/JS_Fun_Practice

Format used for generators are different between tests and examples

g-traub opened this issue · 3 comments

The generator functions (genFrom, genTo, etc) don't have the same return format in the tests and in the examples in the README.md.

In the tests, the format follows the iterator protocol (an object with a next method that returns a value and a done property) and in the examples it only returns a value.

Create JavaScript Generators

To create a generator, you need to first define a generator function with function* symbol. The objects of generator functions are called generators.

The generator function is denoted by . You can either use function generatorFunc() {...} or function *generatorFunc(){...} to create them.

// generator function
function* generatorFunc() {

console.log("1. code before the first yield");
yield 100;

console.log("2. code before the second yield");
yield 200;
}

// returns generator object
const generator = generatorFunc();

console.log(generator.next());

The yield expression returns a value. However, unlike the return statement, it doesn't terminate the program. That's why you can continue executing code from the last yielded position. For example,

function* generatorFunc() {

console.log("1. code before first yield");
yield 100;

console.log("2. code before the second yield");
yield 200;

console.log("3. code after the second yield");

}

const generator = generatorFunc();

console.log(generator.next());
console.log(generator.next());
console.log(generator.next());

Passing Arguments to Generator Functions

You can also pass arguments to a generator function. For example,

// generator function
function* generatorFunc() {

// returns 'hello' at first next()
let x = yield 'hello';

// returns passed argument on the second next()
console.log(x);
console.log('some code');

// returns 5 on second next()
yield 5;

}

const generator = generatorFunc();

console.log(generator.next());
console.log(generator.next(6));
console.log(generator.next());