Creating a set
The current implementation of JavaScript is based on ECMAScript 5.1 (supported by modern browsers) published on June 2011. It contains the Array
class implementation that we covered in earlier chapters. ECMAScript 6 also contains an implementation of the Set
class that you will learn how to use later on in this chapter. The class we will implement in this chapter is based on the Set
implementation of ECMAScript 6.
This is the skeleton of our Set
class:
function Set() { let items = {}; }
A very important detail here is that we are using an object to represent our set (
items
) instead of an array. However, we could also use an array to do this implementation. Let's use an object to implement things a little bit differently and discuss new ways of implementing data structures that are similar. Also, objects in JavaScript do not allow you to have two different properties on the same key, which guarantees unique elements in our set.
Next, we need to declare the methods available...