-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSet.js
118 lines (104 loc) · 2.62 KB
/
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
function Set() {
/**
* Implementation of Set ADT
* Set is a collection of unique elements
* Members of set are unordered and no member of a set can occur twice
*/
var data = [];
this.add = add;
this.remove = remove;
this.size = size;
this.intersect = intersect;
this.union = union;
this.subset = subset;
this.difference = difference;
this.display = display;
var position = 0;
this.hasNext = hasNext;
this.next = next;
this.reset = reset;
this.contains = contains
/**
* Returns a boolean to indicate if the element is added in the set
* @param {*} element
*/
function add(element) {
if(data.indexOf(element) === -1) {
data.push(element);
return true;
}
return false;
};
function remove(element) {
var position = data.indexOf(element);
if(position > -1) {
data.splice(position, 1);
return true;
}
return false;
};
function display() {
return data;
};
function size() {
return data.length;
};
function intersect(set) {
var tempSet = new Set();
while(set.hasNext()) {
var nextElement = set.next();
if(data.indexOf(nextElement) > -1) {
tempSet.add(nextElement);
}
}
set.reset();
return tempSet;
};
function clone() {
var clone = new Set();
for(var i=0; i<data.length; i++) {
clone.add(data[i]);
}
return clone;
};
function union(set) {
var tempSet = clone();
while(set.hasNext()) {
tempSet.add(set.next());
}
set.reset();
return tempSet;
};
function subset(set) {
if(this.size() > set.size()) {
return false;
}
while(this.hasNext()) {
if(!set.contains(this.next())) {
this.reset();
return false;
}
}
return true;
};
function difference(set) {
var tempSet = clone();
while(set.hasNext()) {
tempSet.remove(set.next());
}
set.reset();
return tempSet;
};
function next() {
return data[position++];
};
function hasNext() {
return position < data.length;
};
function reset() {
position = 0;
};
function contains(element) {
return data.indexOf(element) > -1;
};
}