My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Friday, April 17, 2015

A WeakMap Polyfill in 20 lines of code

In case you missed my yesterday post, we finally have a widely compatible cross engine poly for Object.getOwnPropertySymbols(obj).
What I've also tried to epxlain in the very same post, is that Symbol unlocks new patterns for "secret" properties definition, and the following little WeakMap is just one example on how symbols can be used to relate data we don't want to show in other common ways.

var WeakMap = WeakMap || (function (s, dP, hOP) {'use strict';
function WeakMap() { // by Andrea Giammarchi - WTFPL
dP(this, s, {value: Symbol('WeakMap')});
}
WeakMap.prototype = {
'delete': function del(o) {
delete o[this[s]];
},
get: function get(o) {
return o[this[s]];
},
has: function has(o) {
return hOP.call(o, this[s]);
},
set: function set(o, v) {
dP(o, this[s], {configurable: true, value: v});
}
};
return WeakMap;
}(Symbol('WeakMap'), Object.defineProperty, {}.hasOwnProperty));
view raw WeakMap.js hosted with ❤ by GitHub
OK, maybe is not the most perfect polyfill we can have ... but you've got the idea on what could be done through Symbol variables ;-)

No comments: