标签:ret move ase strong value 实现 string arguments log
编码实现js的Set
1 /** 2 * 3 * Set 4 * 5 * @author: 阿宁 6 * 7 * @date: 2017年5月30日 8 * 9 */ 10 (function(global){ 11 12 function Set(){ 13 this.values = {}; 14 this.n = 0; 15 this.add.apply(this,arguments); 16 } 17 18 Set.prototype.add = function(){ 19 for(var i = 0; i < arguments.length; i++){ 20 var val = arguments[i]; 21 var key = Set._v2s(val); 22 if(!this.values.hasOwnProperty(key)){ 23 this.values[key] = val; 24 this.n++; 25 } 26 } 27 return this; 28 }; 29 30 Set.prototype.remove = function(){ 31 for(var i = 0; i < arguments.length; i++){ 32 var key = Set._v2s(arguments[i]); 33 if(this.values.hasOwnProperty(key)){ 34 delete this.values[key]; 35 this.n--; 36 } 37 } 38 return this; 39 }; 40 41 Set.prototype.contain = function(val){ 42 return this.values.hasOwnProperty(Set._v2s(val)); 43 }; 44 45 Set.prototype.foreach = function(f,c){ 46 for(var key in this.values){ 47 if(this.values.hasOwnProperty(key)){ 48 f.call(c,this.values[key]); 49 } 50 } 51 return this; 52 }; 53 54 Set._v2s = function(val){ 55 switch(val){ 56 case undefined:return "u"; 57 case null:return "n"; 58 case true:return "t"; 59 case false: return "f"; 60 default:switch(typeof val){ 61 case "number":return "#" + val; 62 case "string":return "\"" + val; 63 default : return "@" + objectId(val); 64 } 65 } 66 function objectId(val){ 67 var prop = "|**objectid**|"; 68 if(!val.hasOwnProperty(prop)){ 69 val[prop] = Set._v2s.next++; 70 } 71 return val[prop]; 72 } 73 }; 74 75 Set._v2s.next = 100; 76 77 global.Set = Set; 78 79 })(this);
标签:ret move ase strong value 实现 string arguments log
原文地址:http://www.cnblogs.com/ihuning/p/6921754.html