Monday, October 19, 2015

JavaScript Collections - Set

In addition to Map, JavaScript also got another popular collection type this year - the Set. As part of ECMAScript 2015, which is now mostly supported by Node.js, this new build-in object type was added to the language. It's also available on the client-side in Firefox, but it's probably best to keep it on the server side for right now.

So how does it work? Pretty much like you'd expect a Set to work. You can add values to it, but it can only hold unique values (contrast this with Array, which can hold multiple of the same object).

var s = new Set();

s.add("string value");

console.log(s.size); // prints 3

console.log(s.has(4));               // prints true
console.log(s.has("not in there"));  // prints false
console.log(s.has(3+1));             // prints true
console.log(s.has(false));           // prints true

s.add(4);            // no effect
console.log(s.size); // still prints 3

console.log(s.size); // prints 2

As you can see from the example, it supports the standard functions for adding, removing, and checking. Note that, just like Map, the type of objects that can be put in a Set are wide open. You can keep Strings, Numbers, Booleans, and even Functions in the same set. The Booleans are interesting - look at line 5 above. You can add false to the Set. Then s.has(false) returns true. But the fun doesn't end there. You can even put Infinity (NaN) in the Set if you want. Why would you want to? I have no idea, but it works.

var b = new Set();


console.log(b.size); // 1, Infinity added twice

console.log(b.has(1/0)); // prints true

Okay, enough of that. What else should you know about Sets? You can iterate over them just like Arrays.

var c = new Set();



for (i of c) {
    console.log(i); // one, tree, two

The iteration will produce the contents in insertion order, which is why the above example prints one, tree, and then two. There's not really a way to re-order the Set.

Just like I said about Maps, I haven't really been missing them from JavaScript. There's plenty of ways to get around their absence. But now that they're part of the language, I'm sure I'll end up using one somewhere. Personally, I think Sets add more to JavaScript than Maps do simply because of the unique item enforcement.

Don't miss today's comic. Laughter keeps you healthy. comic for 19 October 2015

No comments:

Post a Comment