-
Notifications
You must be signed in to change notification settings - Fork 0
/
HashMap.js
110 lines (98 loc) · 2.05 KB
/
HashMap.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
/**
* Simple hash map class.
* From http://dailyjs.com/2012/09/24/linkedhashmap/
*/
var HashMap = function() {
this._size = 0;
this._map = {};
};
HashMap.prototype = {
/**
* Puts the key/value pair into the map, overwriting
* any existing entry.
*/
put: function(key, value) {
if (!this.containsKey(key)) {
this._size++;
}
this._map[key] = value;
},
/**
* Removes the entry associated with the key
* and returns the removed value.
*/
remove: function(key) {
if (this.containsKey(key)) {
this._size--;
var value = this._map[key];
delete this._map[key];
return value;
} else {
return null;
}
},
/**
* Checks if this map contains the given key.
*/
containsKey: function(key) {
return this._map.hasOwnProperty(key);
},
/**
* Checks if this map contains the given value.
* Note that values are not required to be unique.
*/
containsValue: function(value) {
for (var key in this._map) {
if (this._map.hasOwnProperty(key)) {
if (this._map[key] === value) {
return true;
}
}
}
return false;
},
/**
* Returns the value associated with the given key.
*/
get: function(key) {
return this.containsKey(key) ? this._map[key] : null;
},
/**
* Clears all entries from the map.
*/
clear: function() {
this._size = 0;
this._map = {};
},
/**
* Returns an array of all keys in the map.
*/
keys: function() {
var keys = [];
for (var key in this._map) {
if (this._map.hasOwnProperty(key)) {
keys.push(key);
}
}
return keys;
},
/**
* Returns an array of all values in the map.
*/
values: function() {
var values = [];
for (var key in this._map) {
if (this._map.hasOwnProperty(key)) {
values.push(this._map[key]);
}
}
return values;
},
/**
* Returns the size of the map, which is
* the number of keys.
*/
size: function() {
return this._size;
}
};