internal-state.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 sharedKey = require('../internals/shared-key');
  7. var hiddenKeys = require('../internals/hidden-keys');
  8. var WeakMap = global.WeakMap;
  9. var set, get, has;
  10. var enforce = function (it) {
  11. return has(it) ? get(it) : set(it, {});
  12. };
  13. var getterFor = function (TYPE) {
  14. return function (it) {
  15. var state;
  16. if (!isObject(it) || (state = get(it)).type !== TYPE) {
  17. throw TypeError('Incompatible receiver, ' + TYPE + ' required');
  18. } return state;
  19. };
  20. };
  21. if (NATIVE_WEAK_MAP) {
  22. var store = new WeakMap();
  23. var wmget = store.get;
  24. var wmhas = store.has;
  25. var wmset = store.set;
  26. set = function (it, metadata) {
  27. wmset.call(store, it, metadata);
  28. return metadata;
  29. };
  30. get = function (it) {
  31. return wmget.call(store, it) || {};
  32. };
  33. has = function (it) {
  34. return wmhas.call(store, it);
  35. };
  36. } else {
  37. var STATE = sharedKey('state');
  38. hiddenKeys[STATE] = true;
  39. set = function (it, metadata) {
  40. createNonEnumerableProperty(it, STATE, metadata);
  41. return metadata;
  42. };
  43. get = function (it) {
  44. return objectHas(it, STATE) ? it[STATE] : {};
  45. };
  46. has = function (it) {
  47. return objectHas(it, STATE);
  48. };
  49. }
  50. module.exports = {
  51. set: set,
  52. get: get,
  53. has: has,
  54. enforce: enforce,
  55. getterFor: getterFor
  56. };