Languages
[Edit]
EN

JavaScript - custom implementation of Map class

10 points
Created by:
Welsh
772

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);
});

 

References

  1. Map class - MDN docs
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join