UNPKG

@naturalcycles/js-lib

Version:

Standard library for universal (browser + Node.js) javascript

38 lines (37 loc) 879 B
import { Set2 } from '../object/index.js'; /** * Like Set, but keeps members sorted after every insertion. */ export class SortedSet extends Set2 { constructor(values = [], opt = {}) { super(); this.#comparator = opt.comparator; this.addMany(values); } #comparator; add(value) { if (super.has(value)) { return this; } super.add(value); return this.recreate(); } addMany(items) { for (const item of items) { super.add(item); } return this.recreate(); } recreate() { const items = Array.from(super.values()); items.sort(this.#comparator); super.clear(); for (const item of items) { super.add(item); } return this; } get [Symbol.toStringTag]() { return 'Set'; } }