You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
(function(global){varNaNSymbol=Symbol("NaN");varencodeVal=function(value){returnvalue!==value ? NaNSymbol : value;};vardecodeVal=function(value){returnvalue===NaNSymbol ? NaN : value;};varmakeIterator=function(array,iterator){varnextIndex=0;// new Set(new Set()) 会调用这里varobj={next: function(){returnnextIndex<array.length
? {value: iterator(array[nextIndex++]),done: false}
: {value: void0,done: true};}};// [...set.keys()] 会调用这里obj[Symbol.iterator]=function(){returnobj;};returnobj;};functionforOf(obj,cb){letiterable,result;if(typeofobj[Symbol.iterator]!=="function")thrownewTypeError(obj+" is not iterable");if(typeofcb!=="function")thrownewTypeError("cb must be callable");iterable=obj[Symbol.iterator]();result=iterable.next();while(!result.done){cb(result.value);result=iterable.next();}}functionSet(data){this._values=[];this.size=0;forOf(data,item=>{this.add(item);});}Set.prototype["add"]=function(value){value=encodeVal(value);if(this._values.indexOf(value)==-1){this._values.push(value);++this.size;}returnthis;};Set.prototype["has"]=function(value){returnthis._values.indexOf(encodeVal(value))!==-1;};Set.prototype["delete"]=function(value){varidx=this._values.indexOf(encodeVal(value));if(idx==-1)returnfalse;this._values.splice(idx,1);--this.size;returntrue;};Set.prototype["clear"]=function(value){this._values=[];this.size=0;};Set.prototype["forEach"]=function(callbackFn,thisArg){thisArg=thisArg||global;for(vari=0;i<this._values.length;i++){callbackFn.call(thisArg,this._values[i],this._values[i],this);}};Set.prototype["values"]=Set.prototype["keys"]=function(){returnmakeIterator(this._values,function(value){returndecodeVal(value);});};Set.prototype["entries"]=function(){returnmakeIterator(this._values,function(value){return[decodeVal(value),decodeVal(value)];});};Set.prototype[Symbol.iterator]=function(){returnthis.values();};Set.prototype["forEach"]=function(callbackFn,thisArg){thisArg=thisArg||global;variterator=this.entries();forOf(iterator,item=>{callbackFn.call(thisArg,item[1],item[0],this);});};Set.length=0;global.Set=Set;})(this);
ES6 系列之模拟实现一个 Set 数据结构
Set 函数可以接受一个数组(或者具有 iterable 接口的其他数据结构)作为参数,用来初始化。
操作方法有:
遍历方法有:
注意 keys()、values()、entries() 返回的是遍历器。
属性:
模拟实现一个 Set 数据结构:
测试:
原文链接:ES6 系列之模拟实现一个 Set 数据结构
The text was updated successfully, but these errors were encountered: