File size: 1,136 Bytes
bc20498
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/* global Set */

const undef = typeof undefined;

class ObjectSet {
  constructor( arrayOrObjectSet ){
    this._obj = Object.create(null);
    this.size = 0;

    if( arrayOrObjectSet != null ){
      let arr;

      if( arrayOrObjectSet.instanceString != null && arrayOrObjectSet.instanceString() === this.instanceString() ){
        arr = arrayOrObjectSet.toArray();
      } else {
        arr = arrayOrObjectSet;
      }

      for( let i = 0; i < arr.length; i++ ){
        this.add( arr[i] );
      }
    }
  }

  instanceString(){
    return 'set';
  }

  add( val ){
    let o = this._obj;

    if( o[ val ] !== 1 ){
      o[ val ] = 1;
      this.size++;
    }
  }

  delete( val ){
    let o = this._obj;

    if( o[ val ] === 1 ){
      o[ val ] = 0;
      this.size--;
    }
  }

  clear(){
    this._obj = Object.create(null);
  }

  has( val ){
    return this._obj[ val ] === 1;
  }

  toArray(){
    return Object.keys( this._obj ).filter( key => this.has(key) );
  }

  forEach( callback, thisArg ){
    return this.toArray().forEach( callback, thisArg );
  }
}

export default typeof Set !== undef ? Set : ObjectSet;