internal-metadata.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. var hiddenKeys = require('../internals/hidden-keys');
  2. var isObject = require('../internals/is-object');
  3. var has = require('../internals/has');
  4. var defineProperty = require('../internals/object-define-property').f;
  5. var uid = require('../internals/uid');
  6. var FREEZING = require('../internals/freezing');
  7. var METADATA = uid('meta');
  8. var id = 0;
  9. // eslint-disable-next-line es/no-object-isextensible -- safe
  10. var isExtensible = Object.isExtensible || function () {
  11. return true;
  12. };
  13. var setMetadata = function (it) {
  14. defineProperty(it, METADATA, { value: {
  15. objectID: 'O' + ++id, // object ID
  16. weakData: {} // weak collections IDs
  17. } });
  18. };
  19. var fastKey = function (it, create) {
  20. // return a primitive with prefix
  21. if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
  22. if (!has(it, METADATA)) {
  23. // can't set metadata to uncaught frozen object
  24. if (!isExtensible(it)) return 'F';
  25. // not necessary to add metadata
  26. if (!create) return 'E';
  27. // add missing metadata
  28. setMetadata(it);
  29. // return object ID
  30. } return it[METADATA].objectID;
  31. };
  32. var getWeakData = function (it, create) {
  33. if (!has(it, METADATA)) {
  34. // can't set metadata to uncaught frozen object
  35. if (!isExtensible(it)) return true;
  36. // not necessary to add metadata
  37. if (!create) return false;
  38. // add missing metadata
  39. setMetadata(it);
  40. // return the store of weak collections IDs
  41. } return it[METADATA].weakData;
  42. };
  43. // add metadata on freeze-family methods calling
  44. var onFreeze = function (it) {
  45. if (FREEZING && meta.REQUIRED && isExtensible(it) && !has(it, METADATA)) setMetadata(it);
  46. return it;
  47. };
  48. var meta = module.exports = {
  49. REQUIRED: false,
  50. fastKey: fastKey,
  51. getWeakData: getWeakData,
  52. onFreeze: onFreeze
  53. };
  54. hiddenKeys[METADATA] = true;