internal-state.js 2.0 KB

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