Let’s continue our investigation on what ES6 features are available today (v4.1.0) in Node.
In part 1 we covered block scoping variables and Classes, in this post we’ll cover collections.
As stated in the reference docs “Objects have been used as Maps historically”, but it’s really important we have clear the difference between Map and Object.
While Objects can only map literals to values, with Map can associate value to value.
Let me play the role of Capitan Obvious and say it again: we can now associate objects to objects with no string involved.
Other builtin perks are:
- size and clear come for free, so we don’t have to keep our own counter as a property (and then to exclude it from the count itself…).
- NaN uniqueness , even if NaN === NaN is false, we can use NaN as a unique key
- iterators (entries, values, keys) and a handy forEach method
- has(key) replacing the quirky hasOwnProperty method to check if a key is present
A Set is a collection of non duplicate values.
The main benefit provided by Set is exactly the main purpose it was designed for: filtering out duplicate objects.
I would bet (too) many times we have found ourselves writing code like the following in order not to add twice the same value to an array…
… or even to an object…
And we found out that, unless we put in place a hashing algorithm, or our collection allowed us to use a binary search, we ended up with a linear lookup time that may be not good enough as our collection grows.
Set solves this providing constant lookup time out of the box, and a simple API.
Check yourself this little benchmark, you will notice the difference as the collection grows. (Run it with: “node <filename> <elements amount> <iterations amount>”).
On top of its main purpose, Set comes with several handy utility methods (similar to Map btw…) such as entries, keys and values (keys and values are the SAME function!!!) iterators, size\clear, has to check if the set contains a given value, and the usual forEach.
WeakMap and WeakSet
I’m grouping these up as we already covered Map and Set individually and these two variants of those data structures are very similar to each other.
WeakMap or WeakSet don’t hold a strong reference to the objects they store, hence if the only existing reference to an object is stored in one of these collections the GC will kill it and free that memory location as it passes.
To get a better understanding of garbage collection in take a look to the examples in the reference docs.
When coming to the benefits these weak collections come with, the typical usecase we will stumble upon is about keeping a reference to a DOM object without impeding the GC from collecting it. Even if that gives us an idea of the functionality, it doesn’t fit well to Node.
An example sitting better in this context could be filtering existing collections without keeping a strong reference to each element of the original collection. Consider the following code:
Part 3 will come soon! Watch this space😉