Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Last active November 17, 2020 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WebReflection/21149b526daacbb619006ad17feba805 to your computer and use it in GitHub Desktop.
Save WebReflection/21149b526daacbb619006ad17feba805 to your computer and use it in GitHub Desktop.
WeakMap VS root classes
WeakMap.prototype.hasInherited = function hasInherited(obj) {
let found = false;
while (obj && obj !== Object.prototype && !(found = this.has(obj)))
obj = Object.getPrototypeOf(obj);
return found;
};
WeakMap.prototype.setInherited = function setInherited(obj, value) {
let ref = obj;
while (ref && ref !== Object.prototype) {
const next = Object.getPrototypeOf(ref);
if (!next || next === Object.prototype) {
this.set(ref, value);
break;
}
ref = next;
}
return obj;
};
WeakMap.prototype.getInherited = function getInherited(obj) {
while (obj && !this.has(obj))
obj = Object.getPrototypeOf(obj);
return obj ? this.get(obj) : void 0;
};
// Test Case
class Test {}
const wm = new WeakMap;
const a = new Test;
console.assert(!wm.hasInherited(a), 'wm should not know a');
console.assert(wm.setInherited(a, Math.random()) === a, 'wm should return initial object');
console.assert(wm.hasInherited(a), 'wm should know a');
const b = new Test;
console.assert(wm.hasInherited(b), 'wm should know b');
console.assert(wm.getInherited(a) === wm.getInherited(b), 'wm should return same known value');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment