import * as blueslip from "./blueslip";

export class LazySet {
    /*
        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
        as has/add/delete, we convert it over
        to a set for a one-time cost.
    */

    constructor(vals) {
        this.data = {
            arr: vals,
            set: undefined,
        };
    }

    get size() {
        const {data} = this;
        if (data.set !== undefined) {
            return data.set.size;
        }

        return data.arr.length;
    }

    keys() {
        const {data} = this;
        if (data.set !== undefined) {
            return data.set.keys();
        }
        return data.arr.values();
    }

    _make_set() {
        if (this.data.set !== undefined) {
            return;
        }

        this.data = {
            arr: undefined,
            set: new Set(this.data.arr),
        };
    }

    map(f) {
        return Array.from(this.keys(), f);
    }

    has(v) {
        this._make_set();
        const val = this._clean(v);
        return this.data.set.has(val);
    }

    add(v) {
        this._make_set();
        const val = this._clean(v);
        this.data.set.add(val);
    }

    delete(v) {
        this._make_set();
        const val = this._clean(v);
        return this.data.set.delete(val);
    }

    _clean(v) {
        if (typeof v !== "number") {
            blueslip.error("not a number");
            return Number.parseInt(v, 10);
        }
        return v;
    }
}

@@ -1218,16 +1218,30 @@
   return
+ this.data.set
 ;%0A      
@@ -1338,32 +1338,63 @@
 arr),%0A        %7D;
+%0A%0A        return this.data.set;
 %0A    %7D%0A%0A    map(
@@ -1581,32 +1581,44 @@
 add(v) %7B%0A       
+ const set =
  this._make_set(
@@ -1664,26 +1664,16 @@
         
-this.data.
 set.add(
@@ -1700,32 +1700,44 @@
 ete(v) %7B%0A       
+ const set =
  this._make_set(
@@ -1786,34 +1786,24 @@
      return 
-this.data.
 set.delete(v

Return set from the _make_set method.