internal-state.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. var NATIVE_WEAK_MAP = require('../internals/native-weak-map');
  2. var global = require('../internals/global');
  3. var uncurryThis = require('../internals/function-uncurry-this');
  4. var isObject = require('../internals/is-object');
  5. var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
  6. var hasOwn = require('../internals/has-own-property');
  7. var shared = require('../internals/shared-store');
  8. var sharedKey = require('../internals/shared-key');
  9. var hiddenKeys = require('../internals/hidden-keys');
  10. var OBJECT_ALREADY_INITIALIZED = 'Object already initialized';
  11. var TypeError = global.TypeError;
  12. var WeakMap = global.WeakMap;
  13. var set, get, has;
  14. var enforce = function (it) {
  15. return has(it) ? get(it) : set(it, {});
  16. };
  17. var getterFor = function (TYPE) {
  18. return function (it) {
  19. var state;
  20. if (!isObject(it) || (state = get(it)).type !== TYPE) {
  21. throw TypeError('Incompatible receiver, ' + TYPE + ' required');
  22. } return state;
  23. };
  24. };
  25. if (NATIVE_WEAK_MAP || shared.state) {
  26. var store = shared.state || (shared.state = new WeakMap());
  27. var wmget = uncurryThis(store.get);
  28. var wmhas = uncurryThis(store.has);
  29. var wmset = uncurryThis(store.set);
  30. set = function (it, metadata) {
  31. if (wmhas(store, it)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);
  32. metadata.facade = it;
  33. wmset(store, it, metadata);
  34. return metadata;
  35. };
  36. get = function (it) {
  37. return wmget(store, it) || {};
  38. };
  39. has = function (it) {
  40. return wmhas(store, it);
  41. };
  42. } else {
  43. var STATE = sharedKey('state');
  44. hiddenKeys[STATE] = true;
  45. set = function (it, metadata) {
  46. if (hasOwn(it, STATE)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);
  47. metadata.facade = it;
  48. createNonEnumerableProperty(it, STATE, metadata);
  49. return metadata;
  50. };
  51. get = function (it) {
  52. return hasOwn(it, STATE) ? it[STATE] : {};
  53. };
  54. has = function (it) {
  55. return hasOwn(it, STATE);
  56. };
  57. }
  58. module.exports = {
  59. set: set,
  60. get: get,
  61. has: has,
  62. enforce: enforce,
  63. getterFor: getterFor
  64. };