Skip to content

Instantly share code, notes, and snippets.

@pope
Created October 21, 2008 01:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pope/18227 to your computer and use it in GitHub Desktop.
Save pope/18227 to your computer and use it in GitHub Desktop.
function Set() {
this.data = {};
this.length = 0;
for (var i = 0; i !== arguments.length; i++) {
this.add(arguments[i]);
}
}
(function(proto) {
function eachProp(obj, fn) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
fn(prop);
}
}
}
proto.add = function(obj) {
var $this = this;
if (obj instanceof Set) {
eachProp(obj.data, function(e) { add($this, e); });
} else if (obj instanceof Array) {
eachProp(obj.data, function(e) { add($this, obj[e]); });
} else {
add(this, obj);
}
};
function add(ctx, obj) {
ctx.data[obj] = true;
ctx.length++;
}
proto.remove = function(obj) {
var $this = this;
if (obj instanceof Set) {
eachProp(obj.data, function(e) { remove($this, e); });
} else if (obj instanceof Array) {
eachProp(obj.data, function(e) { remove($this, obj[e]); });
} else {
remove(this, obj);
}
};
function remove(ctx, obj) {
delete ctx.data[obj];
ctx.length--;
}
proto.contains = function(obj) {
return !!(this.get(obj));
};
proto.intersection = function(set) {
var res = new Set();
eachProp(this.data, function(e) {
if (set.data.hasOwnProperty(e)) {
res.add(e);
}
});
return res;
};
proto.union = function(set) {
var res = new Set();
res.add(this);
res.add(set);
return res;
};
proto.difference = function(set) {
var res = new Set();
res.add(this);
res.remove(set);
return res;
};
proto.toArray = function() {
var ret = [];
eachProp(this.data, function(e) { ret.push(e) });
return ret;
};
proto.toString = function() {
return this.toArray().join(",");
};
})(Set.prototype);
var a = new Set(1,3,5), b = new Set(1,2,3);
a.add(7);
print(a.toString());
b.add(4);
print(b.toString());
print(a.union(b).toString());
print(a.intersection(b).toString());
print(a.difference(b).toString());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment