jskatas.org Continuously Learn JavaScript. Your Way.

Generator: send value to a generator

By calling next() with a parameter, you can pass a value to a generator.

Pass a value to a generator

basics: get the values from a generator in two ways
function* generatorFunction() { yield 1; yield 2; } // way #1 var convertedToAnArray = Array.from(generatorFunction()); // way #2 var iterator = generatorFunction(); var iteratedOver = [iterator.next().___, iterator.___]; assert.deepEqual(iteratedOver, convertedToAnArray);
pass a value to the iterator
function* generatorFunction() { yield 1; yield param; } var iterator = generatorFunction(); var iteratedOver = [iterator.next().value, iterator.next(2).value]; assert.deepEqual(iteratedOver, [1, 2]);
a value passed to the 1st next() call is ignored
function* generatorFunction() { yield 1; } let iterator = generatorFunction(); const values = [ iterator.next('irrelevant').value, iterator.next(2).value ]; assert.deepEqual(values, [1, 2]);

Links

The part in the spec, that describes how a generator resumes.

Required Knowledge

Related Katas

Generator

Difficulty Level

ADVANCED

First Published

18 June 2015

Stats

3 tests to solve