Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Set implementation in JavaScript
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
You can’t perform that action at this time.