@rbxts/default-map
v1.0.1
Published
A roblox-ts `Map` wrapper that automatically creates default values for missing keys.
Readme
@rbxts/default-map
A roblox-ts Map wrapper that automatically creates default values for missing keys.
Features
- Automatic default values: When accessing a non-existent key, a default value is created and stored
- Type-safe: Full TypeScript generics support for keys and values
- Standard Map API: Implements familiar
Mapmethods likeget,set,delete,clear,forEach - Always returns a value: The
has()method always returnstruesince any key can be accessed
Installation
npm install @rbxts/default-mapUsage
import { DefaultMap } from "@rbxts/default-map";
// Create a DefaultMap with a default value creator
const counterMap = new DefaultMap(() => 0);
// Accessing a non-existent key creates and returns the default value
counterMap.get("apples"); // Returns 0, creates entry for "apples"
// Increment the counter
counterMap.set("apples", counterMap.get("apples") + 1);
counterMap.get("apples"); // Returns 1
// Works with complex default values
const listMap = new DefaultMap(() => new Array<string>());
listMap.get("fruits").push("apple");
listMap.get("fruits").push("banana");API
Constructor
new DefaultMap<K, V>(defaultValueCreator: () => V, entries?: ReadonlyArray<readonly [K, V]>)defaultValueCreator: Function that creates a new default value when neededentries: Optional initial key-value pairs
Methods
| Method | Description |
|--------|-------------|
| get(key: K): V | Returns the value for key, creating a default if missing |
| set(key: K, value: V): this | Sets the value for key |
| delete(key: K): boolean | Removes the entry for key |
| clear(): void | Removes all entries |
| has(key: K): boolean | Always returns true |
| size(): number | Returns the number of entries |
| isEmpty(): boolean | Returns true if the map has no entries |
| forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void): void | Iterates over all entries |
| getReadonlyRawMap(): ReadonlyMap<K, V> | Returns the underlying Map |
Dependencies
This package has no external dependencies. It only uses the built-in Map type from TypeScript/roblox-ts.
License
MIT
