internal-metadata.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. var isExtensible = Object.isExtensible || function () {
  10. return true;
  11. };
  12. var setMetadata = function (it) {
  13. defineProperty(it, METADATA, { value: {
  14. objectID: 'O' + ++id, // object ID
  15. weakData: {} // weak collections IDs
  16. } });
  17. };
  18. var fastKey = function (it, create) {
  19. // return a primitive with prefix
  20. if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
  21. if (!has(it, METADATA)) {
  22. // can't set metadata to uncaught frozen object
  23. if (!isExtensible(it)) return 'F';
  24. // not necessary to add metadata
  25. if (!create) return 'E';
  26. // add missing metadata
  27. setMetadata(it);
  28. // return object ID
  29. } return it[METADATA].objectID;
  30. };
  31. var getWeakData = function (it, create) {
  32. if (!has(it, METADATA)) {
  33. // can't set metadata to uncaught frozen object
  34. if (!isExtensible(it)) return true;
  35. // not necessary to add metadata
  36. if (!create) return false;
  37. // add missing metadata
  38. setMetadata(it);
  39. // return the store of weak collections IDs
  40. } return it[METADATA].weakData;
  41. };
  42. // add metadata on freeze-family methods calling
  43. var onFreeze = function (it) {
  44. if (FREEZING && meta.REQUIRED && isExtensible(it) && !has(it, METADATA)) setMetadata(it);
  45. return it;
  46. };
  47. var meta = module.exports = {
  48. REQUIRED: false,
  49. fastKey: fastKey,
  50. getWeakData: getWeakData,
  51. onFreeze: onFreeze
  52. };
  53. hiddenKeys[METADATA] = true;