--- id: 8d1323c8c441eddfaeb5bdef title: Create a Set Class challengeType: 1 --- ## Description
In the next few exercises we are going to create a function to emulate a data structure called a "Set". A Set is like an array, but it cannot contain duplicate values. The typical use for a Set is to simply check for the presence of an item. This can be implemented with an object, for instance:
var set = new Object();
set.foo = true;
// See if foo exists in our set:
console.log(set.foo) // true
In the next few exercises, we will build a full featured Set from scratch. For this exercise, create a function that will add a value to our set collection as long as the value does not already exist in the set. For example:
this.add = function(element) {
//some code to add value to the set
}
The function should return true if the value is successfully added and false otherwise.
## Instructions
## Tests
```yml tests: - text: Your Set class should have an add method. testString: 'assert((function(){var test = new Set(); return (typeof test.add === "function")}()), "Your Set class should have an add method.");' - text: Your add method should not add duplicate values. testString: 'assert((function(){var test = new Set(); test.add("a"); test.add("b"); test.add("a"); var vals = test.values(); return (vals[0] === "a" && vals[1] === "b" && vals.length === 2)}()), "Your add method should not add duplicate values.");' - text: Your add method should return true when a value has been successfully added. testString: 'assert((function(){var test = new Set(); var result = test.add("a"); return (result != undefined) && (result === true);}()), "Your add method should return true when a value has been successfully added.");' - text: Your add method should return false when a duplicate value is added. testString: 'assert((function(){var test = new Set(); test.add("a"); var result = test.add("a"); return (result != undefined) && (result === false);}()), "Your add method should return false when a duplicate value is added.");' ```
## Challenge Seed
```js function Set() { // the var collection will hold our set var collection = []; // this method will check for the presence of an element and return true or false this.has = function(element) { return (collection.indexOf(element) !== -1); }; // this method will return all the values in the set this.values = function() { return collection; }; // change code below this line // change code above this line } ```
## Solution
```js function Set() {var collection = []; this.has = function(e){return(collection.indexOf(e) !== -1);};this.values = function() {return collection;};this.add = function(element) {if (!this.has(element)) {collection.push(element);return true;} else {return false;}};} ```