JSlang.dev

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

February 24, 2022
TestsSource
BigInt

Source Code

The source code we wrote during the event.

import {strict as assert} from 'assert';

describe('BigInt basics', () => {
  it('comparing a BigInt with a Number is not the same', () => {
    assert.notEqual(0n, 0);
  });
  it('subtract 0n - 0 will throw', () => {
    assert.throws(() => 0n - 0, TypeError);
  });
  it('subtract 0 - 0n will throw a TypeError', () => {
    assert.throws(() => 0 - 0n, TypeError);
  });
  it('add 0 + 0n will throw a TypeError', () => {
    assert.throws(() => 0 + 0n, TypeError);
  });
  it('adding "0" + 0n will result in "00"', () => {
    assert.equal("0" + 0n, "00");
  });
  it('stringify 0n results in "0"', () => {
    assert.equal(0n.toString(), "0");
  });
});

describe('Number.MAX_*', () => {
  it('multiplying Number.MAX_VALUE * Number.MAX_SAFE_INTEGER is Infinity', () => {
    assert.equal(Number.MAX_VALUE * Number.MAX_SAFE_INTEGER, Infinity);
  });
  it('multiplying BigInts of MAX_VALUE and MAX_SAFE_INTEGER results NOT in Infinity', () => {
    assert.notEqual(BigInt(Number.MAX_VALUE) * BigInt(Number.MAX_SAFE_INTEGER), Infinity);
  });
  it('multiplying BigInts of MAX_VALUE and MAX_SAFE_INTEGER result a BigInt', () => {
    assert.equal(typeof (BigInt(Number.MAX_VALUE) * BigInt(Number.MAX_SAFE_INTEGER)), 'bigint');
  });
  it('BigInt(Number.MAX_VALUE) to the power of BigInt(Number.MAX_VALUE) throws RangeError', () => {
    assert.throws(() => BigInt(Number.MAX_VALUE) ** BigInt(Number.MAX_VALUE), RangeError);
  });

});

describe('JSON and stringify', () => {
  it('stringify 123n throws TypeError', () => {
    assert.throws(() => JSON.stringify([123n]), TypeError);
  });
  it('stringify 123n, which HAS a toJSON method, does NOT throw', () => {
    const bigint = BigInt(123);
    BigInt.prototype.toJSON = () => 'our-123n';
    assert.equal(JSON.stringify(bigint), '"our-123n"');
  });
});