Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Last active December 30, 2022 13:52
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WebReflection/5991636 to your computer and use it in GitHub Desktop.
Save WebReflection/5991636 to your computer and use it in GitHub Desktop.
An alternative, less memory greedy, more robust WeakMap polyfill.
var WeakMap = WeakMap || (function (Object) {
/*! (C) Andrea Giammarchi - Mit Style License */
var
dP = Object.defineProperty,
hOP = Object.hasOwnProperty,
WeakMapPrototype = WeakMap.prototype,
i = 0
;
function WeakMap() {'use strict';
this.clear();
}
WeakMapPrototype.clear = function clear() {
this.name = '__WeakMap#'.concat(++i, Math.random(), '__');
};
WeakMapPrototype['delete'] = function del(key) {
return this.has(key) && delete key[this.name];
};
WeakMapPrototype.get = function get(key) {
return this.has(key) ? key[this.name] : void 0;
};
WeakMapPrototype.has = function has(key) {
return hOP.call(key, this.name);
};
WeakMapPrototype.set = function set(key, value) {
if (this.has(key)) {
key[this.name] = value;
} else {
dP(key, this.name, {
writable: true,
configurable: true,
value: value
});
}
return this;
};
return WeakMap;
}(Object));
@WebReflection
Copy link
Author

full test coverage for what it's provided

var wm = new WeakMap;
var o = {};
var d = {};
console.assert([
  !wm.has(o),
  wm.get(o) === undefined,
  wm.set(o, d) && wm.has(o),
  wm.get(o) === d,
  wm.clear() || !wm.has(o),
  wm.set(d, o) && wm.has(d),
  wm.set(o, d) && wm.has(o),
  wm.get(d) === o,
  wm.delete(o),
  !wm.delete(o),
  wm.delete(d),
  !wm.delete(d),
  !wm.has(o),
  !wm.has(d)
].every(Boolean));

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