@adviser/cement - v0.0.0
    Preparing search index...

    Class KeyedNg<K, V, CTX>

    Generic keyed factory and collection with LRU caching support.

    KeyedNg manages a map of values indexed by keys, where values are created on-demand using a factory function. It provides type-safe key handling, optional LRU eviction, and lifecycle callbacks for monitoring changes.

    This class serves as the foundation for more specialized keyed collections like KeyedResolvOnce and KeyedResolvSeq.

    // Simple factory for objects
    const cache = new KeyedNg({
    createValue: (item) => ({
    id: item.refKey,
    created: Date.now()
    }),
    lru: { max: 100 }
    });

    const obj1 = cache.get('key1');
    const obj2 = cache.get('key2');
    // With complex keys and context
    interface UserKey { org: string; userId: string; }
    interface UserContext { apiKey: string; }

    const users = new KeyedNg<UserKey, User, UserContext>({
    createValue: (item) => new User(item.givenKey, item.ctx),
    key2string: (key) => `${key.org}:${key.userId}`,
    ctx: { apiKey: 'default' }
    });

    const user = users.get(
    { org: 'acme', userId: '123' },
    { apiKey: 'custom' }
    );

    Type Parameters

    • K

      The key type (can be any type with string conversion)

    • V

      The value type created by the factory

    • CTX

      The context type passed to factory and callbacks

    Hierarchy (View Summary)

    Implements

    Index

    Constructors

    Properties

    opts: Required<Omit<KeyedNgOptions<K, V, CTX>, "lru">>

    The resolved options with defaults applied.

    Methods

    • Registers a callback that fires when a new item is added to the collection.

      The callback is invoked after the item is created and stored. Multiple callbacks can be registered.

      Parameters

      • fn: (value: KeyedNgItem<K, V, CTX>) => void

        Callback function receiving the new item

      Returns UnregFn

      Unregister function to remove the callback

      const unregister = keyed.onSet((item) => {
      console.log('Added:', item.givenKey, item.value);
      });

      // Later: remove the callback
      unregister();
    • Registers a callback that fires when an item is deleted from the collection.

      The callback is invoked before the item is removed. This includes both explicit deletions and LRU evictions.

      Parameters

      • fn: (value: KeyedNgItem<K, V, CTX>) => void

        Callback function receiving the deleted item

      Returns UnregFn

      Unregister function to remove the callback

      const unregister = keyed.onDelete((item) => {
      console.log('Removed:', item.givenKey);
      item.value.cleanup?.(); // Perform cleanup if needed
      });
    • Asynchronously gets or creates a value for a key resolved from a promise.

      Useful when the key itself needs to be computed asynchronously, such as from a database lookup or API call.

      Parameters

      • key: () => Promise<K>

        Function returning a promise that resolves to the key

      Returns Promise<V>

      Promise resolving to the value

      const value = await keyed.asyncGet(async () => {
      const id = await fetchUserId();
      return id;
      });
    • Checks if a key exists in the collection.

      Does not create a new value if the key doesn't exist.

      Parameters

      • keyOfFnKey: K | (() => K)

        The key or function returning the key

      Returns boolean

      True if the key exists in the collection

      if (keyed.has('myKey')) {
      console.log('Key exists');
      }

      // With function
      if (keyed.has(() => computeKey())) {
      console.log('Computed key exists');
      }
    • Deletes an item from the collection.

      Triggers onDelete callbacks before removal. The item will need to be recreated if accessed again.

      Parameters

      • key: K

        The key to delete

      Returns void

      keyed.delete('myKey');
      
    • Returns all keys currently in the collection.

      Returns the original keys (givenKey), not the normalized string versions.

      Returns K[]

      Array of all keys

      const keys = keyed.keys();
      console.log(keys); // ['key1', 'key2', 'key3']
    • Iterates over all items in the collection.

      The callback receives each item and its index.

      Parameters

      • fn: (v: KeyedNgItem<K, V, CTX>, idx: number) => void

        Callback function receiving item and index

      Returns void

      keyed.forEach((item, idx) => {
      console.log(idx, item.givenKey, item.value);
      });
    • Returns an iterable of all items with their indices.

      Returns Iterable<[KeyedNgItem<K, V, CTX>, number]>

      Iterable of [item, index] pairs

      for (const [item, idx] of keyed.entries()) {
      console.log(idx, item.givenKey, item.value);
      }
    • Gets or creates the full KeyedNgItem for a given key.

      Returns the complete item structure including key, value, and context. If the key doesn't exist, creates it using the factory function.

      Parameters

      • key: K

        The key to get

      • Optionalctx: CTX

        Optional context override for this get operation

      Returns KeyedNgItem<K, V, CTX>

      The complete KeyedNgItem

      const item = keyed.getItem('myKey', { custom: 'context' });
      console.log(item.refKey, item.givenKey, item.value, item.ctx);
    • Gets or creates a value for the given key.

      This is the primary method for accessing values. If the key doesn't exist, the factory function is called to create the value. Subsequent calls with the same key return the cached value.

      Parameters

      • key: K | (() => K)

        The key or function returning the key

      • Optionalctx: CTX

        Optional context override for this get operation

      Returns V

      The value associated with the key

      // Simple key
      const value1 = keyed.get('myKey');

      // With function
      const value2 = keyed.get(() => computeKey());

      // With custom context
      const value3 = keyed.get('myKey', { custom: 'context' });
    • Returns all items currently in the collection.

      Returns complete KeyedNgItem objects, not just the values.

      Returns KeyedNgItem<K, V, CTX>[]

      Array of all items

      const items = keyed.values();
      items.forEach(item => {
      console.log(item.givenKey, item.value);
      });