EcmaScript Features 10: Set
This week's ES6 feature is the Set. If you know C♯, you'll find the ES6 set to be very similar to C♯'s List class. If not, all will be explained below.
Javascript's Set is essentially a list, with a few differences here and there. You can add things to a set using the .add(thing) function, check whether a Set contains a specific value with the .has(thing) function, and get iterable object full of [key, value] pairs with the .entries() function:
> set = new Set()
Set {}
> set.add("apples")
Set { 'apples' }
> set.add("milk")
Set { 'apples', 'milk' }
> set.add("bronze pineapples")
Set { 'apples', 'milk', 'bronze pineapples' }
> set.has("milk")
true
> set.has("grapefruit")
false
> for(var item of set.entries()) { console.log(item); }
[ 'apples', 'apples' ]
[ 'milk', 'milk' ]
[ 'bronze pineapples', 'bronze pineapples' ]
undefined
Since a Set doesn't really use key value pairs, both the key and the value will be the same, unlike C♯'s List, which uses numbers as the keys for every element inside the List. This leads to an interesting situation. Suppose you try to add two identical things to a list:
> set = new Set()
Set {}
> set.add(1)
Set { 1 }
> set.add(3)
Set { 1, 3 }
> set.add(5)
Set { 1, 3, 5 }
> set.add(5)
Set { 1, 3, 5 }
You would probably expect to see the 5 appear twice in the above example, but it only appears once. What is going on here?
Since the Set uses the values you add to it as the keys when it stores the data for you, it means that if a value you give it is the same as one that you have added before, the key for the new value is the same as the key for the previous value. The result: an iterable object of unique items. You could use the new Set to ensure that your program doesn't have any duplicate entries.
Because the key and the value or any given entry are the same, it means that you have to pass a given entry to the delete function instead of it's index (which it doesn't have) in order to delete it:
> set = new Set()
Set {}
> set.add("piano")
Set { 'piano' }
> set.add("viola")
Set { 'piano', 'viola' }
> set.add("trombone")
Set { 'piano', 'viola', 'trombone' }
> set.delete("viola")
true
> set
Set { 'piano', 'trombone' }
That concludes this post on the ES6: Set. Next time, I will probably take a look at the new strign searching functions and the new number / math related functions.