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); //5
const set2 = new BoundedSet(2, ['Apple', 'Banana', 'Grape']);
console.log(set2.size); //0
console.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 ...

Access this course and 1400+ top-rated courses and projects.