Open
Description
class Set<T> {
private items: any
constructor() {
this.items = {}
}
add(element: T) {
if (!this.has(element)) {
this.items[element] = element
return true
}
return false
}
has(element: T) {
return Object.prototype.hasOwnProperty.call(this.items, element)
}
remove(element: T) {
if (this.has(element)) {
delete this.items[element]
return true
}
return false
}
size() {
return Object.keys(this.items).length
}
clear() {
this.items = {}
}
values() {
return Object.keys(this.items)
}
union(otherSet: Set<T>) {
const set = new Set()
this.values().forEach(value => set.add(value))
otherSet.values().forEach(value => set.add(value))
return set
}
interSection(otherSet: Set<T>) {
const set = new Set()
const values = this.values()
const otherValues = otherSet.values()
let biggerSet = values;
let smallerSet = otherValues;
if (values.length < otherValues.length) {
smallerSet = values
biggerSet = otherValues
}
smallerSet.forEach(v => {
if (biggerSet.includes(v)) set.add(v)
})
return set
}
isSubsetOf(otherSet: Set<T>) {
if (this.size() > otherSet.size()) {
return false;
}
let isSubset = true;
this.values().every((value: any) => {
if (!otherSet.has(value)) {
isSubset = false;
return false;
}
return true;
});
return isSubset;
}
difference(otherSet: Set<T>) {
const set = new Set()
this.values().forEach((value: any) => {
if (!otherSet.has(value)) set.add(value)
})
return set
}
}