Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- export type SetItemComparator<T> = (a: T, b: T) => boolean;
- /**
- *
- */
- export class ComparableSet<T> {
- items: Array<T>;
- comparator: SetItemComparator<T>;
- /**
- *
- * @param items
- * @param comparator
- */
- constructor(items: Array<T> = [], comparator?: SetItemComparator<T>) {
- this.items = items;
- if (comparator) {
- this.comparator = comparator;
- } else {
- // Default comparator
- this.comparator = (a: T, b: T): boolean => a === b;
- }
- }
- /**
- *
- * @param item
- */
- add(item: T): void {
- if (!this.has(item)) {
- this.items.push(item);
- }
- }
- /**
- *
- * @param newSet
- */
- concat(newSet: ComparableSet<T>) {
- newSet.items.forEach(newItem => {
- this.add(newItem);
- });
- }
- /**
- *
- */
- copy(): ComparableSet<T> {
- return new ComparableSet(this.items.slice(0), this.comparator);
- }
- /**
- *
- * @param item
- */
- has(item: T): boolean {
- return this.items.find(setItem => this.comparator(item, setItem)) !== undefined;
- }
- list(): Array<T> {
- return this.items.slice(0);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement