polyfill.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. , randomUniq = require('es5-ext/string/random-uniq')
  6. , d = require('d')
  7. , getIterator = require('es6-iterator/get')
  8. , forOf = require('es6-iterator/for-of')
  9. , toStringTagSymbol = require('es6-symbol').toStringTag
  10. , isNative = require('./is-native-implemented')
  11. , isArray = Array.isArray, defineProperty = Object.defineProperty
  12. , hasOwnProperty = Object.prototype.hasOwnProperty, getPrototypeOf = Object.getPrototypeOf
  13. , WeakMapPoly;
  14. module.exports = WeakMapPoly = function (/*iterable*/) {
  15. var iterable = arguments[0], self;
  16. if (!(this instanceof WeakMapPoly)) throw new TypeError('Constructor requires \'new\'');
  17. if (isNative && setPrototypeOf && (WeakMap !== WeakMapPoly)) {
  18. self = setPrototypeOf(new WeakMap(), getPrototypeOf(this));
  19. } else {
  20. self = this;
  21. }
  22. if (iterable != null) {
  23. if (!isArray(iterable)) iterable = getIterator(iterable);
  24. }
  25. defineProperty(self, '__weakMapData__', d('c', '$weakMap$' + randomUniq()));
  26. if (!iterable) return self;
  27. forOf(iterable, function (val) {
  28. value(val);
  29. self.set(val[0], val[1]);
  30. });
  31. return self;
  32. };
  33. if (isNative) {
  34. if (setPrototypeOf) setPrototypeOf(WeakMapPoly, WeakMap);
  35. WeakMapPoly.prototype = Object.create(WeakMap.prototype, {
  36. constructor: d(WeakMapPoly)
  37. });
  38. }
  39. Object.defineProperties(WeakMapPoly.prototype, {
  40. delete: d(function (key) {
  41. if (hasOwnProperty.call(object(key), this.__weakMapData__)) {
  42. delete key[this.__weakMapData__];
  43. return true;
  44. }
  45. return false;
  46. }),
  47. get: d(function (key) {
  48. if (hasOwnProperty.call(object(key), this.__weakMapData__)) {
  49. return key[this.__weakMapData__];
  50. }
  51. }),
  52. has: d(function (key) {
  53. return hasOwnProperty.call(object(key), this.__weakMapData__);
  54. }),
  55. set: d(function (key, value) {
  56. defineProperty(object(key), this.__weakMapData__, d('c', value));
  57. return this;
  58. }),
  59. toString: d(function () { return '[object WeakMap]'; })
  60. });
  61. defineProperty(WeakMapPoly.prototype, toStringTagSymbol, d('c', 'WeakMap'));