EN
JavaScript - custom implementation of Map class
10 points
In this article, we would like to show how to create custom implementation of Map class in JavaScript.
That implementation may be used in older JavaScript than ES2015, where Map
class is not supported.
The main reason why array and object are used together is added items order keeping.
xxxxxxxxxx
1
function CustomMap() {
2
var map = {};
3
var array = [];
4
this.size = function() {
5
return array.length;
6
};
7
this.exists = function(key) {
8
return key in map;
9
};
10
this.set = function(key, value) {
11
var item = map[key];
12
if (item) {
13
item.value = value;
14
} else {
15
var item = {
16
key: key,
17
value: value
18
};
19
map[key] = item;
20
array.push(item);
21
}
22
};
23
this.get = function(key) {
24
var item = map[key];
25
return item ? item.value : undefined;
26
};
27
this.remove = function(key) {
28
var item = map[key];
29
if (item) {
30
var index = array.indexOf(item);
31
if (index !== -1) {
32
array.splice(index, 1);
33
}
34
delete map[key];
35
}
36
};
37
this.iterate = function(iteration) {
38
for (var i = 0; i < array.length; ++i) {
39
var item = array[i];
40
iteration(i, item.key, item.value);
41
}
42
};
43
}
44
45
46
// Usage example:
47
48
var map = new CustomMap();
49
50
map.set('key 5', 'a');
51
map.set('key 4', 'b');
52
map.set('key 3', 'c');
53
map.set('key 2', 'd');
54
map.set('key 1', 'e');
55
56
map.remove('key 3');
57
58
console.log('map size: ' + map.size());
59
console.log('key 2 -> ' + map.get('key 2'));
60
console.log('key 3 -> ' + map.get('key 3'));
61
console.log('key 4 -> ' + map.get('key 4'));
62
console.log('key 6 -> ' + map.get('key 6'));
63
64
map.iterate(function(index, key, value) {
65
console.log('index: ' + index + ', key: ' + key + ', value: ' + value);
66
});