Maps and Sets
Intro to Maps and Sets
Objects and arrays are common, but JavaScript also provides specialized data
structures for certain jobs:
Map- key/value pairs with any key typeSet- a collection of unique values
These are great for lookups, caching, and deduplication.
Map - key/value lookups
const byId = new Map<string, { name: string }>()
byId.set('u1', { name: 'Ava' })
byId.set('u2', { name: 'Ben' })
const user = byId.get('u1')
// { name: 'Ava' }
Other useful methods:
byId.has('u2')
// true
byId.delete('u2')
// true
byId.size
// 1
Set - unique values
const tags = new Set(['typescript', 'data', 'typescript'])
const uniqueTags = [...tags]
// ['typescript', 'data']
Other useful methods:
tags.has('data')
// true
tags.add('arrays')
tags.delete('typescript')
// true
tags.size
// 2
JavaScript also has WeakMap and WeakSet for object keys that can be
garbage-collected when nothing else references them. We'll just mention them
in passing here, but they're useful for caching without memory leaks.
In this exercise, you'll use
Map for fast lookup and Set for unique values.