2020-02-03 07:48:50 +01:00
|
|
|
export class LazySet {
|
2019-12-27 13:16:22 +01:00
|
|
|
/*
|
|
|
|
This class is optimized for a very
|
|
|
|
particular use case.
|
|
|
|
|
|
|
|
We often have lots of subscribers on
|
|
|
|
a stream. We get an array from the
|
|
|
|
backend, because it's JSON.
|
|
|
|
|
|
|
|
Often the only operation we need
|
|
|
|
on subscribers is to get the length,
|
|
|
|
which is plenty cheap as an array.
|
|
|
|
|
|
|
|
Making an array from a set is cheap
|
|
|
|
for one stream, but it's expensive
|
|
|
|
for all N streams at page load.
|
|
|
|
|
|
|
|
Once somebody does an operation
|
|
|
|
where sets are useful, such
|
2020-02-03 07:41:38 +01:00
|
|
|
as has/add/delete, we convert it over
|
2019-12-27 13:16:22 +01:00
|
|
|
to a set for a one-time cost.
|
|
|
|
*/
|
|
|
|
|
2020-02-03 07:48:50 +01:00
|
|
|
constructor(vals) {
|
|
|
|
this.arr = vals;
|
|
|
|
this.set = undefined;
|
|
|
|
}
|
|
|
|
|
|
|
|
keys() {
|
|
|
|
if (this.set !== undefined) {
|
2020-02-03 08:42:48 +01:00
|
|
|
return this.set.keys();
|
2019-12-27 13:16:22 +01:00
|
|
|
}
|
2020-02-03 08:42:48 +01:00
|
|
|
return this.arr.values();
|
2020-02-03 07:48:50 +01:00
|
|
|
}
|
2019-12-27 13:16:22 +01:00
|
|
|
|
2020-02-03 07:48:50 +01:00
|
|
|
_make_set() {
|
|
|
|
if (this.set !== undefined) {
|
2019-12-27 13:16:22 +01:00
|
|
|
return;
|
|
|
|
}
|
2020-02-03 07:48:50 +01:00
|
|
|
this.set = new Set(this.arr);
|
|
|
|
this.arr = undefined;
|
2019-12-27 13:16:22 +01:00
|
|
|
}
|
|
|
|
|
2020-02-03 07:58:50 +01:00
|
|
|
get size() {
|
2020-02-03 07:48:50 +01:00
|
|
|
if (this.set !== undefined) {
|
|
|
|
return this.set.size;
|
2019-12-27 13:16:22 +01:00
|
|
|
}
|
|
|
|
|
2020-02-03 07:48:50 +01:00
|
|
|
return this.arr.length;
|
|
|
|
}
|
2019-12-27 13:16:22 +01:00
|
|
|
|
2020-02-03 07:48:50 +01:00
|
|
|
map(f) {
|
2020-02-03 08:42:48 +01:00
|
|
|
return Array.from(this.keys(), f);
|
2020-02-03 07:48:50 +01:00
|
|
|
}
|
2019-12-27 13:16:22 +01:00
|
|
|
|
2020-02-03 07:48:50 +01:00
|
|
|
has(v) {
|
|
|
|
this._make_set();
|
|
|
|
const val = this._clean(v);
|
|
|
|
return this.set.has(val);
|
|
|
|
}
|
2019-12-27 13:16:22 +01:00
|
|
|
|
2020-02-03 07:48:50 +01:00
|
|
|
add(v) {
|
|
|
|
this._make_set();
|
|
|
|
const val = this._clean(v);
|
|
|
|
this.set.add(val);
|
|
|
|
}
|
2019-12-27 13:16:22 +01:00
|
|
|
|
2020-02-03 07:48:50 +01:00
|
|
|
delete(v) {
|
|
|
|
this._make_set();
|
|
|
|
const val = this._clean(v);
|
|
|
|
return this.set.delete(val);
|
|
|
|
}
|
2019-12-27 13:16:22 +01:00
|
|
|
|
2020-02-03 07:48:50 +01:00
|
|
|
_clean(v) {
|
2020-01-14 23:29:54 +01:00
|
|
|
if (typeof v !== 'number') {
|
|
|
|
blueslip.error('not a number');
|
|
|
|
return parseInt(v, 10);
|
|
|
|
}
|
|
|
|
return v;
|
2020-02-03 07:48:50 +01:00
|
|
|
}
|
|
|
|
}
|