Skip to Content

References

Codables checks if the same object appears multiple times in the input (including circular references) and automatically preserves object references.

Thanks to that, if you decode the data later, all referential equalities are preserved.

import { encode, decode } from "codables"; const shared = { value: "shared" }; const original = [shared, shared]; const encoded = encode(original); // [{ value: "shared" }, { $$ref: "/0" }] // ^ original ^ reference to the original const decoded = decode(encoded); // decoded[0] === decoded[1]; // true -> (same reference) // original[0] === decoded[0]; // false -> equality is preserved inside the copy of the original data

Circular References

Codables handles circular references automatically:

const parent = { name: "Parent", children: [] }; const child = { name: "Child", parent }; parent.children.push(child); const encoded = encode(parent); // { // name: "Parent", // children: [{ name: "Child", parent: { $$ref: "/" } }] // } const decoded = decode(encoded); // decoded.children[0].parent === decoded (circular reference preserved)

Disabling Reference Preservation

Sometimes you want to disable reference preservation to create independent copies:

const shared = { value: "shared" }; const data = [shared, shared]; const encoded = encode(data, { preserveReferences: false }); // [{ value: "shared" }, { value: "shared" }] // ^ no reference created const decoded = decode(encoded); // decoded[0] !== decoded[1] (different objects)

Custom Types with References

References work seamlessly with custom types as well:

class Node { constructor(public value: string, public parent?: Node) {} } const $$node = createCodableType( "Node", (value) => value instanceof Node, (node) => ({ value: node.value, parent: node.parent }), (data) => new Node(data.value, data.parent) ); const coder = new Coder([$$node]); const parent = new Node("parent"); const child = new Node("child", parent); const encoded = coder.encode([parent, child]); // [ // { $$Node: { value: "parent", parent: undefined } }, // { $$Node: { value: "child", parent: { $$ref: "/0" } } } // ]
Last updated on