Last active
December 30, 2022 13:52
-
-
Save WebReflection/5991636 to your computer and use it in GitHub Desktop.
An alternative, less memory greedy, more robust WeakMap polyfill.
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
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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
full test coverage for what it's provided