2
0

polyfill.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. 'use strict';
  2. var setPrototypeOf = require('es5-ext/object/set-prototype-of')
  3. , object = require('es5-ext/object/valid-object')
  4. , value = require('es5-ext/object/valid-value')
  5. , d = require('d')
  6. , getIterator = require('es6-iterator/get')
  7. , forOf = require('es6-iterator/for-of')
  8. , toStringTagSymbol = require('es6-symbol').toStringTag
  9. , isNative = require('./is-native-implemented')
  10. , isArray = Array.isArray, defineProperty = Object.defineProperty, random = Math.random
  11. , hasOwnProperty = Object.prototype.hasOwnProperty
  12. , genId, WeakMapPoly;
  13. genId = (function () {
  14. var generated = Object.create(null);
  15. return function () {
  16. var id;
  17. do { id = random().toString(36).slice(2); } while (generated[id]);
  18. generated[id] = true;
  19. return id;
  20. };
  21. }());
  22. module.exports = WeakMapPoly = function (/*iterable*/) {
  23. var iterable = arguments[0];
  24. if (!(this instanceof WeakMapPoly)) return new WeakMapPoly(iterable);
  25. if (this.__weakMapData__ !== undefined) {
  26. throw new TypeError(this + " cannot be reinitialized");
  27. }
  28. if (iterable != null) {
  29. if (!isArray(iterable)) iterable = getIterator(iterable);
  30. }
  31. defineProperty(this, '__weakMapData__', d('c', '$weakMap$' + genId()));
  32. if (!iterable) return;
  33. forOf(iterable, function (val) {
  34. value(val);
  35. this.set(val[0], val[1]);
  36. }, this);
  37. };
  38. if (isNative) {
  39. if (setPrototypeOf) setPrototypeOf(WeakMapPoly, WeakMap);
  40. WeakMapPoly.prototype = Object.create(WeakMap.prototype, {
  41. constructor: d(WeakMapPoly)
  42. });
  43. }
  44. Object.defineProperties(WeakMapPoly.prototype, {
  45. clear: d(function () {
  46. defineProperty(this, '__weakMapData__', d('c', '$weakMap$' + genId()));
  47. }),
  48. delete: d(function (key) {
  49. if (hasOwnProperty.call(object(key), this.__weakMapData__)) {
  50. delete key[this.__weakMapData__];
  51. return true;
  52. }
  53. return false;
  54. }),
  55. get: d(function (key) {
  56. if (hasOwnProperty.call(object(key), this.__weakMapData__)) {
  57. return key[this.__weakMapData__];
  58. }
  59. }),
  60. has: d(function (key) {
  61. return hasOwnProperty.call(object(key), this.__weakMapData__);
  62. }),
  63. set: d(function (key, value) {
  64. defineProperty(object(key), this.__weakMapData__, d('c', value));
  65. return this;
  66. }),
  67. toString: d(function () { return '[object WeakMap]'; })
  68. });
  69. defineProperty(WeakMapPoly.prototype, toStringTagSymbol, d('c', 'WeakMap'));