TemplateLiteral.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = extractValueFromTemplateLiteral;
  6. function sortStarts(a, b) {
  7. return (a.range ? a.range[0] : a.start) - (b.range ? b.range[0] : b.start);
  8. }
  9. /**
  10. * Returns the string value of a template literal object.
  11. * Tries to build it as best as it can based on the passed
  12. * prop. For instance `This is a ${prop}` will return 'This is a {prop}'.
  13. *
  14. * If the template literal builds to undefined (`${undefined}`), then
  15. * this should return "undefined".
  16. */
  17. function extractValueFromTemplateLiteral(value) {
  18. var quasis = value.quasis,
  19. expressions = value.expressions;
  20. var partitions = quasis.concat(expressions);
  21. return partitions.sort(sortStarts).reduce(function (raw, part) {
  22. var type = part.type;
  23. if (type === 'TemplateElement') {
  24. return raw + part.value.raw;
  25. }
  26. if (type === 'Identifier') {
  27. return part.name === 'undefined' ? '' + raw + part.name : raw + '{' + part.name + '}';
  28. }
  29. if (type.indexOf('Expression') > -1) {
  30. return raw + '{' + type + '}';
  31. }
  32. return raw;
  33. }, '');
  34. }