Last active
November 17, 2020 12:47
-
-
Save WebReflection/21149b526daacbb619006ad17feba805 to your computer and use it in GitHub Desktop.
WeakMap VS root classes
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
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