2018-10-12 15:37:13 -04:00
|
|
|
---
|
|
|
|
title: Create a Set Class
|
|
|
|
---
|
2019-07-24 00:59:27 -07:00
|
|
|
# Create a Set Class
|
2018-10-12 15:37:13 -04:00
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
---
|
|
|
|
## Problem Explanation
|
2018-11-25 23:26:33 +05:30
|
|
|
- A Set is an abstract data structure.
|
|
|
|
- It can store unique value and the collection is unordered.
|
|
|
|
- In this challenge, we have to implement `.add()` method. This method should only add unique values to `collection`.
|
|
|
|
- The method should return `true`, if the value is sucessfully added to the collection, otherwise it should return `false`.
|
2018-10-12 15:37:13 -04:00
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
|
|
|
|
---
|
|
|
|
## Solutions
|
|
|
|
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
|
|
|
|
2018-11-25 23:26:33 +05:30
|
|
|
```js
|
|
|
|
function Set() {
|
2019-07-24 00:59:27 -07:00
|
|
|
// 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;
|
|
|
|
};
|
|
|
|
this.add = function(el) {
|
|
|
|
return this.has(el) ? false : Boolean(collection.push(el));
|
|
|
|
};
|
2018-11-25 23:26:33 +05:30
|
|
|
}
|
|
|
|
```
|
2018-10-12 15:37:13 -04:00
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
#### Relevant Links
|
2018-11-25 23:26:33 +05:30
|
|
|
- [Wikipedia](https://en.wikipedia.org/wiki/Set_(abstract_data_type))
|
2019-07-24 00:59:27 -07:00
|
|
|
|
|
|
|
</details>
|