es.symbol.description.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // `Symbol.prototype.description` getter
  2. // https://tc39.github.io/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 has = require('../internals/has');
  8. var isObject = require('../internals/is-object');
  9. var defineProperty = require('../internals/object-define-property').f;
  10. var copyConstructorProperties = require('../internals/copy-constructor-properties');
  11. var NativeSymbol = global.Symbol;
  12. if (DESCRIPTORS && typeof NativeSymbol == 'function' && (!('description' in NativeSymbol.prototype) ||
  13. // Safari 12 bug
  14. NativeSymbol().description !== undefined
  15. )) {
  16. var EmptyStringDescriptionStore = {};
  17. // wrap Symbol constructor for correct work with undefined description
  18. var SymbolWrapper = function Symbol() {
  19. var description = arguments.length < 1 || arguments[0] === undefined ? undefined : String(arguments[0]);
  20. var result = this instanceof SymbolWrapper
  21. ? new NativeSymbol(description)
  22. // in Edge 13, String(Symbol(undefined)) === 'Symbol(undefined)'
  23. : description === undefined ? NativeSymbol() : NativeSymbol(description);
  24. if (description === '') EmptyStringDescriptionStore[result] = true;
  25. return result;
  26. };
  27. copyConstructorProperties(SymbolWrapper, NativeSymbol);
  28. var symbolPrototype = SymbolWrapper.prototype = NativeSymbol.prototype;
  29. symbolPrototype.constructor = SymbolWrapper;
  30. var symbolToString = symbolPrototype.toString;
  31. var native = String(NativeSymbol('test')) == 'Symbol(test)';
  32. var regexp = /^Symbol\((.*)\)[^)]+$/;
  33. defineProperty(symbolPrototype, 'description', {
  34. configurable: true,
  35. get: function description() {
  36. var symbol = isObject(this) ? this.valueOf() : this;
  37. var string = symbolToString.call(symbol);
  38. if (has(EmptyStringDescriptionStore, symbol)) return '';
  39. var desc = native ? string.slice(7, -1) : string.replace(regexp, '$1');
  40. return desc === '' ? undefined : desc;
  41. }
  42. });
  43. $({ global: true, forced: true }, {
  44. Symbol: SymbolWrapper
  45. });
  46. }