forked from loiane/javascript-datastructures-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path01-Set.js
136 lines (114 loc) · 3.1 KB
/
01-Set.js
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
/**
* ECMSCRIPT 6 already have a Set class implementation:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
* We will try to copy the same functionalities
* @constructor
*/
function Set() {
var items = {};
this.add = function(value){
if (!this.has(value)){
items[value] = value;
return true;
}
return false;
};
this.remove = function(value){
if (this.has(value)){
delete items[value];
return true;
}
return false;
};
this.has = function(value){
return items.hasOwnProperty(value);
//return value in items;
};
this.clear = function(){
items = {};
};
/**
* Modern browsers function
* IE9+, FF4+, Chrome5+, Opera12+, Safari5+
* @returns {Number}
*/
this.size = function(){
return Object.keys(items).length;
};
/**
* cross browser compatibility - legacy browsers
* for modern browsers use size function
* @returns {number}
*/
this.sizeLegacy = function(){
var count = 0;
for(var prop in items) {
if(items.hasOwnProperty(prop))
++count;
}
return count;
};
/**
* Modern browsers function
* IE9+, FF4+, Chrome5+, Opera12+, Safari5+
* @returns {Array}
*/
this.values = function(){
return Object.keys(items);
};
this.valuesLegacy = function(){
var keys = [];
for(var key in items){
keys.push(key);
}
return keys;
};
this.getItems = function(){
return items;
};
this.union = function(otherSet){
var unionSet = new Set(); //{1}
var values = this.values(); //{2}
for (var i=0; i<values.length; i++){
unionSet.add(values[i]);
}
values = otherSet.values(); //{3}
for (var i=0; i<values.length; i++){
unionSet.add(values[i]);
}
return unionSet;
};
this.intersection = function(otherSet){
var intersectionSet = new Set(); //{1}
var values = this.values();
for (var i=0; i<values.length; i++){ //{2}
if (otherSet.has(values[i])){ //{3}
intersectionSet.add(values[i]); //{4}
}
}
return intersectionSet;
};
this.difference = function(otherSet){
var differenceSet = new Set(); //{1}
var values = this.values();
for (var i=0; i<values.length; i++){ //{2}
if (!otherSet.has(values[i])){ //{3}
differenceSet.add(values[i]); //{4}
}
}
return differenceSet;
};
this.subset = function(otherSet){
if (this.size() > otherSet.size()){ //{1}
return false;
} else {
var values = this.values();
for (var i=0; i<values.length; i++){ //{2}
if (!otherSet.has(values[i])){ //{3}
return false; //{4}
}
}
return true;
}
};
}