MatrixAI / js-id

ID generation for JavaScript & TypeScript Applications
https://polykey.com
Apache License 2.0
10 stars 1 forks source link

Adding toJSON, fromJSON and equals to IdInternal #12

Closed CMCDragonkai closed 2 years ago

CMCDragonkai commented 2 years ago

Description

This adds the methods of toJSON, fromJSONand equals.

The JSON methods matches the behaviour of Node's buffer. It allows us to marshal IdInternal into JSON and back with the appropriate reviver.

    const id = IdInternal.create([97, 98, 99]);
    const json = JSON.stringify(id);
    const id_ = JSON.parse(json, (k, v) => {
      return IdInternal.fromJSON(v) ?? v;
    });

Notice that JSON.stringify does not need a special replacer. This is already done by having a toJSON method in the IdInternal class.

In the case of JSON.parse, when it will convert any { type: 'IdInternal', data: [ ... ] } into the IdInternal object.

This is important as in some cases, when storing Ids where JSON is expected, this allow us to unmarshal back to the canonical binary ID representation rather than always encoding it as a string.

The above reviver will default if it's not an valid IdInternal object.

Additionally the equals method provides an efficient way to check for IdInternal equality.

    const id1 = IdInternal.create([97, 98, 99]);
    const id2 = IdInternal.create([97, 98, 99]);
    const id3 = IdInternal.create([97, 98, 100]);
    expect(id1.equals(id2)).toBe(true);
    expect(id1.equals(id3)).toBe(false);

Issues Fixed

Tasks

  1. [x] Added toJSON and fromJSON and tests
  2. [x] Added equals and tests
  3. [x] Ensured that fromJSON can be used inside the reviver of JSON.parse

Final checklist

CMCDragonkai commented 2 years ago

@tegefaulkes @joshuakarp. This is ready to be used and will be released as 3.3.0. You can replace any equality comparison in the src code with equals instead of converting to binary string.

Furthermore, the toJSON may not be used for now because you're using NodeIdEncoded, but this gives us the opportunity to change if we need to.

CMCDragonkai commented 2 years ago

Some fixes for the previous PR too.

  1. fromString doesn't return undefined, any binary string is valid Id
  2. fromBuffer doesn't return undefined, any buffer is valid Id

This means some ! assertions may not be needed.

@tegefaulkes