Solution Review: Sets
Let's discuss the solution to the set implementation challenge given in the previous lesson.
We'll cover the following...
Solution
The solution to the challenge given in the previous lesson is given below.
Press + to interact
'use strict';class BoundedSet extends Set {constructor(capacity, initialValues) {super();this.capacity = capacity;if(initialValues.length <= capacity) {initialValues.forEach(value => this.add(value));}}add(value) {if(this.has(value)) return;if(this.size < this.capacity) {super.add(value);} else {throw new Error(`exceeded capacity of ${this.capacity} elements`);}}}const set = new BoundedSet(5, ['Apple', 'Banana', 'Grape', 'Mango']);set.add('Orange');set.add('Apple');try {set.add('Tangerine');} catch(ex) {console.log(ex.message); //exceeded capacity of 5 elements}set.delete('Grape');set.add('Peach');console.log(set.size); //5const set2 = new BoundedSet(2, ['Apple', 'Banana', 'Grape']);console.log(set2.size); //0console.log(set2.capacity); //capacity
Explanation
Let’s start the implementation of BoundedSet
by defining the constructor.
Constructor
As you know from the object instantiation given at line 24 and line 38; there are two constructor parameters.
-
The first argument is an integer indicating the total number of elements a set can have, so we call it
capacity
. -
The second argument is an array consisting of the array of values that we are calling
initialValues
, ...