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.
Practical example
The main reason why array and object are used together is added items order keeping.
// ONLINE-RUNNER:browser;
function CustomMap() {
var map = {};
var array = [];
this.size = function() {
return array.length;
};
this.exists = function(key) {
return key in map;
};
this.set = function(key, value) {
var item = map[key];
if (item) {
item.value = value;
} else {
var item = {
key: key,
value: value
};
map[key] = item;
array.push(item);
}
};
this.get = function(key) {
var item = map[key];
return item ? item.value : undefined;
};
this.remove = function(key) {
var item = map[key];
if (item) {
var index = array.indexOf(item);
if (index !== -1) {
array.splice(index, 1);
}
delete map[key];
}
};
this.iterate = function(iteration) {
for (var i = 0; i < array.length; ++i) {
var item = array[i];
iteration(i, item.key, item.value);
}
};
}
// Usage example:
var map = new CustomMap();
map.set('key 5', 'a');
map.set('key 4', 'b');
map.set('key 3', 'c');
map.set('key 2', 'd');
map.set('key 1', 'e');
map.remove('key 3');
console.log('map size: ' + map.size());
console.log('key 2 -> ' + map.get('key 2'));
console.log('key 3 -> ' + map.get('key 3'));
console.log('key 4 -> ' + map.get('key 4'));
console.log('key 6 -> ' + map.get('key 6'));
map.iterate(function(index, key, value) {
console.log('index: ' + index + ', key: ' + key + ', value: ' + value);
});