Skip to content

Commit e34d53a

Browse files
committed
Added a Set data structure.
1 parent 8d01f78 commit e34d53a

1 file changed

Lines changed: 108 additions & 0 deletions

File tree

v3/src/structs/Set.js

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
var Set = function ()
2+
{
3+
this.values = [];
4+
};
5+
6+
Set.prototype.constructor = Set;
7+
8+
Set.prototype = {
9+
10+
add: function (value)
11+
{
12+
if (this.values.indexOf(value) === -1)
13+
{
14+
this.values.push(value);
15+
}
16+
},
17+
18+
delete: function (value)
19+
{
20+
var index = this.values.indexOf(value);
21+
22+
if (index > -1)
23+
{
24+
this.values.splice(index, 1);
25+
}
26+
},
27+
28+
clear: function ()
29+
{
30+
this.values.length = 0;
31+
},
32+
33+
contains: function (value)
34+
{
35+
return (this.values.indexOf(value) > -1);
36+
},
37+
38+
union: function (set)
39+
{
40+
var newSet = new Set();
41+
42+
set.values.forEach(function (value)
43+
{
44+
newSet.add(value);
45+
});
46+
47+
this.values.forEach(function (value)
48+
{
49+
newSet.add(value);
50+
});
51+
52+
return newSet;
53+
},
54+
55+
intersect: function (set)
56+
{
57+
var newSet = new Set();
58+
59+
this.values.forEach(function (value)
60+
{
61+
if (set.contains(value))
62+
{
63+
newSet.add(value);
64+
}
65+
});
66+
67+
return newSet;
68+
},
69+
70+
difference: function (set)
71+
{
72+
var newSet = new Set();
73+
74+
this.values.forEach(function (value)
75+
{
76+
if (!set.contains(value))
77+
{
78+
newSet.add(value);
79+
}
80+
});
81+
82+
return newSet;
83+
}
84+
85+
};
86+
87+
Object.defineProperties(Set.prototype, {
88+
89+
length: {
90+
91+
writable: true,
92+
enumerable: false,
93+
94+
get: function ()
95+
{
96+
return this.values.length;
97+
},
98+
99+
set: function (value)
100+
{
101+
return this.values.length = value;
102+
}
103+
104+
}
105+
106+
});
107+
108+
module.exports = Set;

0 commit comments

Comments
 (0)