1 |
|
2 |
|
3 | const undef = typeof undefined;
|
4 |
|
5 | class ObjectSet {
|
6 | constructor( arrayOrObjectSet ){
|
7 | this._obj = Object.create(null);
|
8 | this.size = 0;
|
9 |
|
10 | if( arrayOrObjectSet != null ){
|
11 | let arr;
|
12 |
|
13 | if( arrayOrObjectSet.instanceString != null && arrayOrObjectSet.instanceString() === this.instanceString() ){
|
14 | arr = arrayOrObjectSet.toArray();
|
15 | } else {
|
16 | arr = arrayOrObjectSet;
|
17 | }
|
18 |
|
19 | for( let i = 0; i < arr.length; i++ ){
|
20 | this.add( arr[i] );
|
21 | }
|
22 | }
|
23 | }
|
24 |
|
25 | instanceString(){
|
26 | return 'set';
|
27 | }
|
28 |
|
29 | add( val ){
|
30 | let o = this._obj;
|
31 |
|
32 | if( o[ val ] !== 1 ){
|
33 | o[ val ] = 1;
|
34 | this.size++;
|
35 | }
|
36 | }
|
37 |
|
38 | delete( val ){
|
39 | let o = this._obj;
|
40 |
|
41 | if( o[ val ] === 1 ){
|
42 | o[ val ] = 0;
|
43 | this.size--;
|
44 | }
|
45 | }
|
46 |
|
47 | clear(){
|
48 | this._obj = Object.create(null);
|
49 | }
|
50 |
|
51 | has( val ){
|
52 | return this._obj[ val ] === 1;
|
53 | }
|
54 |
|
55 | toArray(){
|
56 | return Object.keys( this._obj ).filter( key => this.has(key) );
|
57 | }
|
58 |
|
59 | forEach( callback, thisArg ){
|
60 | return this.toArray().forEach( callback, thisArg );
|
61 | }
|
62 | }
|
63 |
|
64 | export default typeof Set !== undef ? Set : ObjectSet;
|