Skip to content

Instantly share code, notes, and snippets.

@xulapp
Created June 25, 2011 16:53
Show Gist options
  • Select an option

  • Save xulapp/1046657 to your computer and use it in GitHub Desktop.

Select an option

Save xulapp/1046657 to your computer and use it in GitHub Desktop.
weakmap allowed primitive key
function WeakDict() {
var map = WeakMap();
Object.defineProperty(map, '__dict__', {
value: Object.create(null),
writable: true,
configuable: true,
});
map.__proto__ = WeakDict.prototype;
return map;
}
WeakDict.prototype = Object.create(WeakMap.prototype, {
constructor: {
value: WeakDict,
writable: true,
configuable: true,
},
has: {
value: function has(key) {
if (key instanceof Object)
return WeakMap.prototype.has.apply(this, arguments);
return key in this.__dict__;
},
writable: true,
configuable: true,
},
get: {
value: function get(key, def) {
if (key instanceof Object)
return WeakMap.prototype.get.apply(this, arguments);
return key in this.__dict__ ? this.__dict__[key] : def;
},
writable: true,
configuable: true,
},
set: {
value: function set(key, val) {
if (key instanceof Object)
return WeakMap.prototype.set.apply(this, arguments);
return this.__dict__[key] = val;
},
writable: true,
configuable: true,
},
delete: {
value: function delete(key) {
if (key instanceof Object)
return WeakMap.prototype.delete.apply(this, arguments);
var has = key in this.__dict__;
delete this.__dict__[key];
return has;
},
writable: true,
configuable: true,
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment