index.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var callBound = require('call-bound');
  4. var $SyntaxError = require('es-errors/syntax');
  5. var getGlobalSymbolDescription = GetIntrinsic('%Symbol.keyFor%', true);
  6. /** @type {undefined | ((thisArg: symbol | Symbol) => symbol)} */
  7. var thisSymbolValue = callBound('%Symbol.prototype.valueOf%', true);
  8. /** @type {undefined | ((thisArg: symbol | Symbol) => string)} */
  9. var symToStr = callBound('Symbol.prototype.toString', true);
  10. /** @type {(thisArg: string, start?: number, end?: number) => string} */
  11. var $strSlice = callBound('String.prototype.slice');
  12. var getInferredName = require('./getInferredName');
  13. /** @type {import('.')} */
  14. /* eslint-disable consistent-return */
  15. module.exports = callBound('%Symbol.prototype.description%', true) || function getSymbolDescription(symbol) {
  16. if (!thisSymbolValue) {
  17. throw new $SyntaxError('Symbols are not supported in this environment');
  18. }
  19. // will throw if not a symbol primitive or wrapper object
  20. var sym = thisSymbolValue(symbol);
  21. if (getInferredName) {
  22. var name = getInferredName(sym);
  23. if (name === '') {
  24. return;
  25. }
  26. return name.slice(1, -1); // name.slice('['.length, -']'.length);
  27. }
  28. var desc;
  29. if (getGlobalSymbolDescription) {
  30. desc = getGlobalSymbolDescription(sym);
  31. if (typeof desc === 'string') {
  32. return desc;
  33. }
  34. }
  35. // eslint-disable-next-line no-extra-parens
  36. desc = $strSlice(/** @type {NonNullable<typeof symToStr>} */ (symToStr)(sym), 7, -1); // str.slice('Symbol('.length, -')'.length);
  37. if (desc) {
  38. return desc;
  39. }
  40. };