JSlang.dev

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

August 10, 2017
TestsSource
Generators

Source Code

The source code we wrote during the event.

import assert from 'assert';

/*

- Show progress for data transmission
- When packet was delivered successfully 
  increase packet size 2 times
- When packet was not delivered successfully 
  decrease the packet size to 1
- When there is no connection stop transmission 
  and continue from the beginning, once the 
  connection occurs again
*/

describe('Transmitting a file of 10 chars, with initial package size 1 char', () => {
  const generatorFunction = function*({file}) {
    let progress = (transmitted) => transmitted / file.length;
    let packageSize = 1;
    let sentBits = 0;
    let maybePackageSize;

    while (true) {
      if (sentBits + packageSize > file.length) return progress(file.length);
      maybePackageSize = yield progress(sentBits + packageSize);
      sentBits += packageSize;
      packageSize = maybePackageSize || packageSize;
    } 
  };
  
  let generator;
  beforeEach(() => {
    generator = generatorFunction({file: '1234567890'});
  })
  
  it('the first transmission returns the progress 1/10', () => {
    const {value:progress} = generator.next();
    assert.equal(progress, 0.1);
  });
  it('the 2nd transmission returns the progress 2/10', () => {
    generator.next();
    const {value:progress} = generator.next();
    assert.equal(progress, 0.2);
  });
  it('the 3nd transmission returns the progress 3/10', () => {
    generator.next();
    generator.next();
    const {value:progress} = generator.next();
    assert.equal(progress, 0.3);
  });
  it('the 11th transmission returns 10/10', () => {
    generator.next();
    generator.next();
    generator.next();
    generator.next();
    generator.next();
    generator.next();
    generator.next();
    generator.next();
    generator.next();
    generator.next();
    const {value:progress} = generator.next();
    assert.equal(progress, 1);
  });
  
  describe('we set the package size', () => {
    it('by 2chars, the 3nd transmission returns the progress 4/10', () => {
      generator.next();
      generator.next();
      const {value:progress} = generator.next(2);
      assert.equal(progress, 0.4);
    });
    it('by 4chars, the 2nd transmission returns the progress 5/10', () => {
      generator.next();
      const {value:progress} = generator.next(4);
      assert.equal(progress, 0.5);
    });
    it('by 4chars, the 3nd transmission returns the progress 9/10', () => {
      generator.next();
      generator.next(4);
      const {value:progress} = generator.next();
      assert.equal(progress, 0.9);
    });
    it('by 4chars, the 4nd transmission returns the progress 10/10', () => {
      generator.next();
      generator.next(4);
      generator.next();
      const {value:progress} = generator.next();
      assert.equal(progress, 1);
    });
  })
});