-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhashtable.js
73 lines (64 loc) · 1.21 KB
/
hashtable.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
function HashTable(objs) {
// Constructing Stuff
this.length = 0;
this.items = {};
for (var i in objs) {
if (objs.hasOwnProperty(i)) {
this.items[i] = objs[i];
this.length++;
}
}
this.setItem = function(key, value) {
var prev;
if (this.hasItem(key)) {
prev = this.items[key];
} else {
this.length++;
}
this.items[key] = value;
return prev;
};
this.getItem = function(key) {
return this.hasItem(key) ? this.items[key] : undefined;
};
this.hasItem = function(key) {
return this.items.hasOwnProperty(key);
};
this.removeItem = function(key) {
if (this.hasItem(key)) {
var prev = this.getItem(key);
this.length--;
delete this.items[key];
return prev;
}
return undefined;
};
this.keys = function() {
var keys = [];
for (var k in this.items) {
if (this.hasItem(k)) {
keys.push(k);
}
}
return keys;
};
this.values = function() {
var values = [];
for (var k in this.items) {
if (this.hasItem(k)) {
values.push(this.getItem(k));
}
}
};
this.each = function(callback) {
for (var k in this.items) {
if (this.hasItem(k)) {
callback(k, this.getItem(k));
}
}
};
this.clear = function() {
this.items = {};
this.length = 0;
};
}