Skip to content

Instantly share code, notes, and snippets.

@tcstory
Created October 19, 2016 09:01
Show Gist options
  • Save tcstory/ac6c25bedf83a646d5fe72fba97479e1 to your computer and use it in GitHub Desktop.
Save tcstory/ac6c25bedf83a646d5fe72fba97479e1 to your computer and use it in GitHub Desktop.
class Set {
constructor() {
this._items = {};
}
add(value) {
if (!this.has(value)) {
this._items[value] = value;
return true;
}
return false;
}
remove(value) {
if (this.has(value)) {
delete this._items[value];
return true;
}
return false;
}
has(value) {
return this._items.hasOwnProperty(value);
}
clear() {
this._items = {};
}
get size() {
return Object.keys(this._items).length;
}
values() {
return Object.keys(this._items);
}
union(otherSet) {
let unionSet = new Set();
let values = this.values();
for (let i = 0, len = values.length; i < len; i++) {
unionSet.add(values[i]);
}
values = otherSet.values();
for (let i = 0, len = values.length; i < len; i++) {
unionSet.add(values[i]);
}
return unionSet;
}
intersection(otherSet) {
let intersectionSet = new Set();
let values = this.values();
for (let i = 0, len = values.length; i < len; i++) {
if (otherSet.has(values[i])) {
intersectionSet.add(values[i]);
}
}
return intersectionSet;
}
difference(otherSet) {
let differenceSet = new Set();
let values = this.values();
for (let i = 0, len = values.length; i < len; i++) {
if (!otherSet.has(values[i])) {
differenceSet.add(values[i]);
}
}
return differenceSet;
}
subset(otherSet) {
if (this.size > otherSet.size) {
return false;
} else {
let values = this.values();
for (let i = 0, len = values.length; i < len; i++) {
if (!otherSet.has(values[i])) {
return false;
}
}
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment