Created
April 3, 2014 17:38
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 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
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
It does matter if someone calls
set
with"__proto__"
as thekey
.