es.symbol.description.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // `Symbol.prototype.description` getter
  2. // https://tc39.es/ecma262/#sec-symbol.prototype.description
  3. 'use strict';
  4. var $ = require('../internals/export');
  5. var DESCRIPTORS = require('../internals/descriptors');
  6. var global = require('../internals/global');
  7. var uncurryThis = require('../internals/function-uncurry-this');
  8. var hasOwn = require('../internals/has-own-property');
  9. var isCallable = require('../internals/is-callable');
  10. var isPrototypeOf = require('../internals/object-is-prototype-of');
  11. var toString = require('../internals/to-string');
  12. var defineBuiltInAccessor = require('../internals/define-built-in-accessor');
  13. var copyConstructorProperties = require('../internals/copy-constructor-properties');
  14. var NativeSymbol = global.Symbol;
  15. var SymbolPrototype = NativeSymbol && NativeSymbol.prototype;
  16. if (DESCRIPTORS && isCallable(NativeSymbol) && (!('description' in SymbolPrototype) ||
  17. // Safari 12 bug
  18. NativeSymbol().description !== undefined
  19. )) {
  20. var EmptyStringDescriptionStore = {};
  21. // wrap Symbol constructor for correct work with undefined description
  22. var SymbolWrapper = function Symbol() {
  23. var description = arguments.length < 1 || arguments[0] === undefined ? undefined : toString(arguments[0]);
  24. var result = isPrototypeOf(SymbolPrototype, this)
  25. ? new NativeSymbol(description)
  26. // in Edge 13, String(Symbol(undefined)) === 'Symbol(undefined)'
  27. : description === undefined ? NativeSymbol() : NativeSymbol(description);
  28. if (description === '') EmptyStringDescriptionStore[result] = true;
  29. return result;
  30. };
  31. copyConstructorProperties(SymbolWrapper, NativeSymbol);
  32. SymbolWrapper.prototype = SymbolPrototype;
  33. SymbolPrototype.constructor = SymbolWrapper;
  34. var NATIVE_SYMBOL = String(NativeSymbol('description detection')) === 'Symbol(description detection)';
  35. var thisSymbolValue = uncurryThis(SymbolPrototype.valueOf);
  36. var symbolDescriptiveString = uncurryThis(SymbolPrototype.toString);
  37. var regexp = /^Symbol\((.*)\)[^)]+$/;
  38. var replace = uncurryThis(''.replace);
  39. var stringSlice = uncurryThis(''.slice);
  40. defineBuiltInAccessor(SymbolPrototype, 'description', {
  41. configurable: true,
  42. get: function description() {
  43. var symbol = thisSymbolValue(this);
  44. if (hasOwn(EmptyStringDescriptionStore, symbol)) return '';
  45. var string = symbolDescriptiveString(symbol);
  46. var desc = NATIVE_SYMBOL ? stringSlice(string, 7, -1) : replace(string, regexp, '$1');
  47. return desc === '' ? undefined : desc;
  48. }
  49. });
  50. $({ global: true, constructor: true, forced: true }, {
  51. Symbol: SymbolWrapper
  52. });
  53. }