WeakMap.ts 1.2 KB

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