Search⌘ K
AI Features

Solution Review: Sets

Understand how to create and manage bounded Sets in JavaScript by using constructors with capacity and initial values. Learn to add elements conditionally, check for duplicates, and remove items while ensuring the set size respects defined limits. This lesson reinforces key concepts of inheritance and built-in Set methods.

We'll cover the following...

Solution

The solution to the challenge given in the previous lesson is given below.

Javascript (babel-node)
'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 parameters.

  1. The first argument is an integer indicating the total number of elements a set can have, so we call it capacity.

  2. The second argument is an array consisting of the array of values that we are calling initialValues, ...