internal-state.js 1.9 KB

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