Class WeakOption<B, T>

A WeakMap-based implementation of the Option pattern for handling optional values. This class provides safe access to values that may or may not exist, using WeakMap for automatic garbage collection when the base object is no longer referenced.

const option = new WeakOption<MyObject, string>();
const obj = new MyObject();
option.set(obj, "hello");
const value = option.unwrapOrDefault(obj, "default"); // Returns "hello"

Type Parameters

  • B extends object

    The base object type used as a key in the WeakMap

  • T

    The type of the value being stored

Implements

Constructors

Methods

  • Checks if a value exists for the given base object.

    Parameters

    • base: B

      The base object used as a key

    Returns boolean

    True if the value exists, false otherwise

  • Sets a value for the given base object.

    Parameters

    • base: B

      The base object to use as a key

    • val: T

      The value to store

    Returns void

  • Unwraps the value or returns a default value if it doesn't exist.

    Parameters

    • base: B

      The base object used as a key

    • altValue: T

      The alternative value to return if the value doesn't exist

    Returns T

    The stored value or the alternative value

  • Unwraps the value or executes a function to get an alternative value.

    Parameters

    • base: B

      The base object used as a key

    • f: ((...vals: any) => T)

      Function to execute if the value doesn't exist

        • (...vals): T
        • Parameters

          • Rest...vals: any

          Returns T

    Returns T

    The stored value or the result of the function