JSlang.dev

JavaScript Deep Dives with Wolfram. Since 2015
Inclusive, Test-Driven, Spec-Focused, Collaborative.

August 18, 2022
TestsSource
JavaScript Generators

Source Code

The source code we wrote during the event.

import {strict as assert} from 'assert';

describe('what is a generator/iterator', () => {
  it('a generator is an object', () => {
    const generatorFunction = function*(){}
    const generator = generatorFunction();
    assert.equal(typeof generator, 'object');
  });
  it('a generator function is of type "function"', () => {
    const generatorFunction = function*() {};
    assert.equal(typeof generatorFunction, 'function');
  });
  it('a generator is an instance of generator function', () => {
    const generatorFunction = function*() {}
    const generator = generatorFunction();
    assert(generator instanceof generatorFunction);
  });

  it('a generator has a `next` method', () => {
    const generatorFunction = function*() {}
    const generator = generatorFunction();
    assert.equal(typeof generator.next, 'function');
  });
  it('the next method of a generator yielding one value returns a result with that value', () => {
    const generatorFunction = function*() { yield 23; }
    const generator = generatorFunction()
    assert.equal(generator.next().value, 23);
  });
  it('the next method of a generator returns done=true when it is completed', () => {
    const generatorFunction = function*() {}
    const generator = generatorFunction()
    assert.equal(generator.next().done, true);
  });
  it('calling `next()` on a 1-element generator, returns `done=false`', () => {
    const generator = (function*() { yield 1; })();
    assert.equal(generator.next().done, false);
  });

  it('throwing an exception inside the generator function, calling next(), propogates the error', () => {
    const generator = (function*() { throw new Error('oh mg'); })();
    assert.throws(() => generator.next(), { name: 'Error', message: 'oh mg'});
  });
});