Now we’ve learned about the following complex data structures:
- Objects for storing keyed collections.
- Arrays for storing ordered collections.
But that’s not enough for real life. That’s why Map and Set also exist.
Map
Map is a collection of keyed data items, just like an Object. But the main difference is that Map allows keys of any type.
Methods and properties are:
- new Map() – creates the map.
- map.set(key, value) – stores the value by the key.
- map.get(key) – returns the value by the key, undefined if key doesn’t exist in map.
- map.has(key) – returns true if the key exists, false otherwise.
- map.delete(key) – removes the value by the key.
- map.clear() – removes everything from the map.
- map.size – returns the current element count.
For instance:
Map can also use objects as keys.
Every map.set call returns the map itself, so we can “chain” the calls:
Iteration over Map
For looping over a map, there are 3 methods:
- map.keys() – returns an iterable for keys,
- map.values() – returns an iterable for values,
- map.entries() – returns an iterable for entries [key, value],
Set
A Set is a special type collection – “set of values” (without keys), where each value may occur only once.
Its main methods are:
- new Set(iterable) – creates the set, and if an iterable object is provided (usually an array), copies values from it into the set.
- set.add(value) – adds a value, returns the set itself.
- set.delete(value) – removes the value, returns true if value existed at the moment of the call, otherwise false.
- set.has(value) – returns true if the value exists in the set, otherwise false.
- set.clear() – removes everything from the set.
- set.size – is the elements count.
The main feature is that repeated calls of set.add(value) with the same value don’t do anything. That’s the reason each value appears in a Set only once.
For example, we have visitors coming, and we’d like to remember everyone. But repeated visits should not lead to duplicates. A visitor must be “counted” only once.
Set is just the right thing for that:
0 comments:
Post a Comment