Created
October 27, 2021 19:12
-
-
Save cagataycali/f62ec46169af044f58723d359058c4ea to your computer and use it in GitHub Desktop.
[JavaScript] Implement Set data type
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* The Set object lets you store unique values of any type, whether primitive values or object references. | |
| Resource: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set | |
| Set has 6 methods; | |
| new Set | |
| add(item) | |
| delete(item) | |
| has(item) | |
| forEach(callbackFunction) | |
| values() // Returns array of items. | |
| Set has 1 property which is, | |
| size: Returns number of elements in a Set. | |
| */ | |
| // Old school way to create class. | |
| // Usage: new Set([1, 2, 3]); | |
| function Set (items = []) { | |
| // O(n) | Reducer creates hashmap from that array. | |
| this.items = items.reduce((previousValue, currentValue) => (previousValue = {...previousValue, [currentValue]: 1}),{}); | |
| // O(n) | Read whole object keys, | |
| this.size = Object.keys(this.items).length; | |
| }; | |
| Set.prototype.has = function (item) { | |
| return item in this.items; | |
| }; | |
| Set.prototype.add = function (item) { | |
| if (this.has(item)) return; | |
| this.items[item] = 1; | |
| this.size++; | |
| return this; | |
| }; | |
| Set.prototype.delete = function (item) { | |
| if (!this.has(item)) return; | |
| delete this.items[item]; | |
| this.size--; | |
| return this; | |
| }; | |
| Set.prototype.forEach = function (callbackFunction) { | |
| Object.keys(this.items).forEach(callbackFunction); | |
| }; | |
| Set.prototype.values = function () { | |
| return Object.keys(this.items); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment