WeakMap.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. var wmUniqueIndex = Math.round(Math.random() * 9);
  2. var supportDefineProperty = typeof Object.defineProperty === 'function';
  3. var WeakMap = (function () {
  4. function WeakMap() {
  5. this._id = '__ec_inner_' + wmUniqueIndex++;
  6. }
  7. WeakMap.prototype.get = function (key) {
  8. return this._guard(key)[this._id];
  9. };
  10. WeakMap.prototype.set = function (key, value) {
  11. var target = this._guard(key);
  12. if (supportDefineProperty) {
  13. Object.defineProperty(target, this._id, {
  14. value: value,
  15. enumerable: false,
  16. configurable: true
  17. });
  18. }
  19. else {
  20. target[this._id] = value;
  21. }
  22. return this;
  23. };
  24. WeakMap.prototype["delete"] = function (key) {
  25. if (this.has(key)) {
  26. delete this._guard(key)[this._id];
  27. return true;
  28. }
  29. return false;
  30. };
  31. WeakMap.prototype.has = function (key) {
  32. return !!this._guard(key)[this._id];
  33. };
  34. WeakMap.prototype._guard = function (key) {
  35. if (key !== Object(key)) {
  36. throw TypeError('Value of WeakMap is not a non-null object.');
  37. }
  38. return key;
  39. };
  40. return WeakMap;
  41. }());
  42. export default WeakMap;