get-value-if-string.js 1004 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /**
  2. * @author Toru Nagashima
  3. * @copyright 2016 Toru Nagashima. All rights reserved.
  4. * See LICENSE file in root directory for full license.
  5. */
  6. "use strict"
  7. //------------------------------------------------------------------------------
  8. // Public Interface
  9. //------------------------------------------------------------------------------
  10. /**
  11. * Gets the value of a given node if it's a literal or a template literal.
  12. *
  13. * @param {ASTNode} node - A node to get.
  14. * @returns {string|null} The value of the node, or `null`.
  15. */
  16. module.exports = function getValueIfString(node) {
  17. if (!node) {
  18. return null
  19. }
  20. switch (node.type) {
  21. case "Literal":
  22. if (typeof node.value === "string") {
  23. return node.value
  24. }
  25. break
  26. case "TemplateLiteral":
  27. if (node.expressions.length === 0) {
  28. return node.quasis[0].value.cooked
  29. }
  30. break
  31. // no default
  32. }
  33. return null
  34. }