DefaultMap
A map that automatically creates values for missing keys using a factory function.
Similar to Python's defaultdict.
@example
// Group items by category using arrays
const groupByCategory = new DefaultMap<string, string[]>(() => [])
groupByCategory.get('fruits').push('apple', 'banana')
groupByCategory.get('vegetables').push('carrot')
groupByCategory.get('fruits').push('orange')
console.log(groupByCategory.get('fruits')) // ['apple', 'banana', 'orange']
console.log(groupByCategory.get('vegetables')) // ['carrot']
console.log(groupByCategory.get('dairy')) // [] (auto-created)
@example
// Build a graph with adjacency lists
const graph = new DefaultMap<string, Set<string>>(() => new Set())
graph.get('A').add('B').add('C')
graph.get('B').add('C').add('D')
graph.get('C').add('D')
console.log([...graph.get('A')]) // ['B', 'C']
console.log([...graph.get('B')]) // ['C', 'D']
console.log([...graph.get('E')]) // [] (auto-created empty set)
@example
// Initialize with existing entries
const scores = new DefaultMap<string, number>(
() => 0,
[
['Alice', 100],
['Bob', 85]
]
)
scores.set('Alice', scores.get('Alice') + 10) // 100 -> 110
console.log(scores.get('Alice')) // 110
console.log(scores.get('Bob')) // 85
console.log(scores.get('Charlie')) // 0 (auto-created)
@example
// Nested DefaultMaps for 2D data structures
const matrix = new DefaultMap<number, DefaultMap<number, number>>(
() => new DefaultMap<number, number>(() => 0)
)
matrix.get(0).set(0, 1)
matrix.get(0).set(1, 2)
matrix.get(1).set(1, 3)
console.log(matrix.get(0).get(0)) // 1
console.log(matrix.get(0).get(1)) // 2
console.log(matrix.get(1).get(0)) // 0 (auto-created)
console.log(matrix.get(2).get(3)) // 0 (both auto-created)
class DefaultMap<K, V> extends Map<K, V> { }
constructor(defaultFactory: () => V, iterable?: Iterable<readonly [K, V]>);
private readonly defaultFactory;
get(key: K): V;