JSlang.dev

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

January 20, 2022
TestsSource
DataView

Source Code

The source code we wrote during the event.

import {strict as assert} from 'assert';

it('ArrayBuffer and DataView exist on nodejs?', () => {
  assert.doesNotThrow(() => { new ArrayBuffer(1); });
  assert.equal(typeof globalThis.DataView, 'function');
});

describe('buffer is (im)mutable?', () => {
  it('verifies that ArrayBuffer is mutable', () => {
    const buf = new ArrayBuffer(1);
    new DataView(buf).setInt8(0, 42);
    assert.equal(new Int8Array(buf)[0], 42);
  });
});

describe('endianness', () => {
  it('little endianness for 2-byte word, is the last byte first', () => {
    const dataView = new DataView(new ArrayBuffer(2));
    dataView.setUint16(0, 256+255, true); // 0000 0001 1111 1111
    assert.equal(dataView.getUint8(0), 255); // 1111 1111
    assert.equal(dataView.getUint8(1), 1); // 0000 0001
  });
  it('big endianness for a 2-byte word, is the first byte first', () => {
    const dataView = new DataView(new ArrayBuffer(2));
    dataView.setUint16(0, 256, false); // 0000 0001 0000 0000
    assert.equal(dataView.getUint8(0), 1);
    assert.equal(dataView.getUint8(1), 0);
  });
  describe('4 bytes', () => {
    const dataView = new DataView(new ArrayBuffer(4));
    it('big endianness, are stored first, second, third and fourth byte', () => {
      dataView.setUint32(0, 0b0000_0111_0000_0011_0000_0001_0000_0000, false);
      assert.equal(dataView.getUint8(0), 0b0000_0111);
      assert.equal(dataView.getUint8(1), 0b0000_0011);
      assert.equal(dataView.getUint8(2), 0b0000_0001);
      assert.equal(dataView.getUint8(3), 0b0000_0000);
    });
    it('little endianness, are stored fourth, third, second and first byte', () => {
      dataView.setUint32(0, 0b0000_0111_0000_0011_0000_0001_0000_0000, true);
      assert.equal(dataView.getUint8(0), 0b0000_0000);
      assert.equal(dataView.getUint8(1), 0b0000_0001);
      assert.equal(dataView.getUint8(2), 0b0000_0011);
      assert.equal(dataView.getUint8(3), 0b0000_0111);
    });
  });
});

describe('de/encoding using ArrayBuffer/DataView? base64, etc.', () => {
  it('', () => {

  });
});