Created
September 2, 2016 09:43
-
-
Save nvurgaft/e60fdfa3d6a9ba2d66324aa976f8238a to your computer and use it in GitHub Desktop.
Set implementation in JavaScript
This file contains 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
var ISet = function(array) { | |
this.list = array ? toSet(array) : []; | |
}; | |
ISet.prototype.add = function(inValue) { | |
if (exists(this.list, inValue) < 0) { | |
this.list.push(inValue); | |
return true; | |
} | |
return false; | |
}; | |
ISet.prototype.remove = function(item) { | |
var idx = exists(this.list, item); | |
if (idx > 0) { | |
this.list.splice(idx, 1); | |
} | |
return idx > 0; | |
}; | |
ISet.prototype.getValues = function() { | |
return this.list; | |
} | |
ISet.prototype.toSet = function(array) { | |
return toSet(array); | |
} | |
function toSet(array) { | |
var copy = [].concat(array); | |
for (var i = 0; i < copy.length; i++) { | |
for (var j = i + 1; j < copy.length; j++) { | |
if (copy[i] === copy[j]) { | |
copy.splice(j--, 1); | |
} | |
} | |
} | |
return copy; | |
} | |
ISet.prototype.size = function() { | |
return this.list.length; | |
}; | |
ISet.prototype.clear = function() { | |
this.list = []; | |
}; | |
function exists(list, item) { | |
for (var i = 0; i < list.length; i++) { | |
if (list[i] === item) { | |
return i; | |
} | |
} | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment