Skip to content

Instantly share code, notes, and snippets.

@nzakas
Created April 3, 2014 17:38
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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;
}
};
@cowboy
Copy link

cowboy commented Apr 3, 2014

Why not SimpleMap.prototype = Object.create(null, {...}); so that instances don't also inherit from Object.prototype? Or are you targeting ES3?

@cowboy
Copy link

cowboy commented Apr 3, 2014

Actually, I guess it doesn't matter, since you'd never enumerate instance properties.

@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