ts-data-forge
    Preparing search index...
    • Creates a new ISetMapped instance with custom element transformation functions.

      This factory function creates an immutable set that can use complex objects as elements by providing bidirectional transformation functions. The toKey function converts your custom element type to a primitive type that can be efficiently stored, while fromKey reconstructs the original element type for iteration and access.

      Performance: O(n) where n is the number of elements in the iterable.

      Type Parameters

      • K

        The type of the custom elements.

      • KM extends Primitive

        The type of the mapped primitive keys.

      Parameters

      • iterable: Iterable<K>

        An iterable of elements using the custom element type.

      • toKey: (a: K) => KM

        A function that converts a custom element K to a primitive key KM. This function must be deterministic and produce unique values for unique elements.

      • fromKey: (k: KM) => K

        A function that converts a primitive key KM back to the custom element K. This should be the inverse of toKey.

      Returns ISetMapped<K, KM>

      A new ISetMapped instance containing all unique elements from the iterable.

      type Point = Readonly<{ x: number; tag: string }>;

      const toKey = (point: Point) => JSON.stringify(point);

      // eslint-disable-next-line total-functions/no-unsafe-type-assertion
      const fromKey = (key: string) => JSON.parse(key) as Point;

      const set = ISetMapped.create<Point, string>(
      [
      { x: 1, tag: 'a' },
      { x: 1, tag: 'a' },
      { x: 2, tag: 'b' },
      ],
      toKey,
      fromKey,
      );

      assert.deepStrictEqual(Array.from(set), [
      { x: 1, tag: 'a' },
      { x: 2, tag: 'b' },
      ]);