Skip to content

Instantly share code, notes, and snippets.

@nvurgaft
Created September 2, 2016 09:43
Show Gist options
  • Save nvurgaft/e60fdfa3d6a9ba2d66324aa976f8238a to your computer and use it in GitHub Desktop.
Save nvurgaft/e60fdfa3d6a9ba2d66324aa976f8238a to your computer and use it in GitHub Desktop.
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