Skip to content

Instantly share code, notes, and snippets.

@nzakas
Created April 3, 2014 17:38
Show Gist options
  • Save nzakas/9959066 to your computer and use it in GitHub Desktop.
Save nzakas/9959066 to your computer and use it in GitHub Desktop.
A simple map implementation for JavaScript (not intended to be an ES6 polyfill)
function SimpleMap() {
this._data = {};
}
SimpleMap.prototype = {
get: function(key) {
return this.has(key) ? this._data[key] : null;
},
has: function(key) {
return Object.prototype.hasOwnProperty.call(this._data, key);
},
set: function(key, value) {
this._data[key] = value;
}
};
@fitzgen
Copy link

fitzgen commented Apr 3, 2014

It does matter if someone calls set with "__proto__" as the key.

@WebReflection
Copy link

@fitzgen that can break regardless so a more robust version could be:

function SimpleMap() {  
    this._data = {};
}

SimpleMap.prototype = {

    get: function(key) {
        return this.has(key) ? this._data['@' + key] : void 0;
    },

    has: function(key) {
        return this.hasOwnProperty.call(this._data, '@' + key);
    },

    set: function(key, value) {
        this._data['@' + key] = value;
    }
};

Although this is nothing better than just Object.create(null) but yeah, latter one might need a little polyfill

@nzakas
Copy link
Author

nzakas commented Apr 4, 2014

My goal in creating this was for a project that had to work in IE < 9, so I couldn't use Object.create().

I like @WebReflection's alternative.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment