@naturalcycles/js-lib
Version:
Standard library for universal (browser + Node.js) javascript
42 lines (41 loc) • 1.01 kB
JavaScript
/**
* Like Set, but serializes to JSON as an array.
*
* Fixes the "issue" of stock Set being json-serialized as `{}`.
*
* @experimental
*/
export class Set2 extends Set {
static of(items) {
return new Set2(items);
}
/**
* Like .add(), but allows to add multiple items at once.
* Mutates the Set, but also returns it conveniently.
*/
addMany(items) {
for (const item of items) {
this.add(item);
}
return this;
}
first() {
if (!this.size)
throw new Error('Set.first called on empty set');
return this.firstOrUndefined();
}
firstOrUndefined() {
return this.values().next().value;
}
// Last is not implemented, because it requires to traverse the whole Set - not optimal
// last(): T {
toArray() {
return [...this];
}
toJSON() {
return [...this];
}
toString() {
return `Set2(${this.size}) ${JSON.stringify([...this])}`;
}
}