UNPKG

scats

Version:

Useful scala classes in typescript

84 lines (83 loc) 1.87 kB
import { AbstractSet } from '../abstract-set.js'; import * as immutable from '../hashset.js'; export class HashSet extends AbstractSet { constructor(items = new Set()) { super(items); } static of(...items) { return new HashSet(new Set(items)); } static from(values) { return HashSet.of(...Array.from(values)); } fromArray(array) { return HashSet.of(...array); } add(elem) { const res = this.items.has(elem); if (!res) { this.items.add(elem); return true; } else { return !res; } } addAll(xs) { for (const x of xs) { this.items.add(x); } return this; } subtractAll(xs) { for (const x of xs) { this.items.delete(x); } return this; } remove(elem) { const res = this.items.has(elem); if (res) { this.items.delete(elem); return true; } else { return res; } } filterInPlace(p) { if (this.nonEmpty) { const arr = this.toArray; for (const t of arr) { if (!p(t)) { this.remove(t); } } } return this; } clear() { this.items.clear(); } addOne(elem) { this.add(elem); return this; } subtractOne(elem) { this.remove(elem); return this; } concat(that) { const newSet = new Set([...this.items, ...that]); return new HashSet(newSet); } intersect(that) { return this.filter(x => that.contains(x)); } union(that) { return this.concat(that); } get toImmutable() { return immutable.HashSet.of(...this.items); } }