stringify.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. function stringifyNode(node, custom) {
  2. var type = node.type;
  3. var value = node.value;
  4. var buf;
  5. var customResult;
  6. if (custom && (customResult = custom(node)) !== undefined) {
  7. return customResult;
  8. } else if (type === "word" || type === "space") {
  9. return value;
  10. } else if (type === "string") {
  11. buf = node.quote || "";
  12. return buf + value + (node.unclosed ? "" : buf);
  13. } else if (type === "comment") {
  14. return "/*" + value + (node.unclosed ? "" : "*/");
  15. } else if (type === "div") {
  16. return (node.before || "") + value + (node.after || "");
  17. } else if (Array.isArray(node.nodes)) {
  18. buf = stringify(node.nodes, custom);
  19. if (type !== "function") {
  20. return buf;
  21. }
  22. return (
  23. value +
  24. "(" +
  25. (node.before || "") +
  26. buf +
  27. (node.after || "") +
  28. (node.unclosed ? "" : ")")
  29. );
  30. }
  31. return value;
  32. }
  33. function stringify(nodes, custom) {
  34. var result, i;
  35. if (Array.isArray(nodes)) {
  36. result = "";
  37. for (i = nodes.length - 1; ~i; i -= 1) {
  38. result = stringifyNode(nodes[i], custom) + result;
  39. }
  40. return result;
  41. }
  42. return stringifyNode(nodes, custom);
  43. }
  44. module.exports = stringify;