javascript——集合類
10648 ワード
1 /**
2 * Created by Administrator on 2015/4/14.
3 */
4 function Set() {
5 this.values = {};
6 this.n = 0;
7 this.add.apply(this, arguments);
8 }
9 Set.prototype = {
10 add: function () {
11 for (var i = 0; i < arguments.length; i++) {
12 var val = arguments[i];
13 var str = Set._v2s(val);
14 if (!this.values.hasOwnProperty(str)) {
15 this.values[str] = val;
16 this.n++;
17 }
18 }
19 return this;
20 },
21 remove: function () {
22 for (var i = 0; i < arguments.length; i++) {
23 var str = Set._v2s(arguments[i]);
24 if (this.values.hasOwnProperty(str)) {
25 delete this.values[str];
26 this.n--;
27 }
28 }
29 return this;
30 },
31 contains: function (value) {
32 return this.values.hasOwnProperty(Set._v2s(value));
33 },
34 size: function () {
35 return this.n;
36 },
37 foreach: function (f, context) {
38 for (var s in this.values) {
39 if (this.values.hasOwnProperty(s)) {
40 f.call(context, this.values[s]);
41 }
42 }
43 }
44 };
45 Set={
46 // , javascript
47 _v2s: function (val) {
48 switch(val){
49 case undefined: return 'u';
50 case null:return 'n';
51 case true:return 't';
52 case false: return 'f';
53 default :switch (typeof val){
54 case 'number':return '#'+val;
55 case 'string':return '"'+val;
56 default :return '@'+objectId(val);
57 }
58 }
59 //
60 // ,
61 // ,
62 function objectId(o){
63 var prop="|**objectid**|";
64 if(!o.hasOwnProperty(prop)){
65 o[prop]=Set._v2s.next++;
66 }
67 return o[prop];
68 };
69 }
70 };
71
72 // 100
73 Set._v2s.next=100;