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" Copy
const option = new WeakOption<MyObject, string>();const obj = new MyObject();option.set(obj, "hello");const value = option.unwrapOrDefault(obj, "default"); // Returns "hello"
The base object type used as a key in the WeakMap
The type of the value being stored
Checks if a value exists for the given base object.
The base object used as a key
True if the value exists, false otherwise
Sets a value for the given base object.
The base object to use as a key
The value to store
Forcefully unwraps the value, throwing an error if it doesn't exist.
The stored value
When the value doesn't exist
Unwraps the value or returns a default value if it doesn't exist.
The alternative value to return if the value doesn't exist
The stored value or the alternative value
Unwraps the value or executes a function to get an alternative value.
Function to execute if the value doesn't exist
Rest
The stored value or the result of the function
Unwraps the value or returns undefined if it doesn't exist.
The stored value or undefined
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.
Example