You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.6 KiB

4 years ago
  1. var sourceMap = require('./sourceMap');
  2. var hasOwnProperty = Object.prototype.hasOwnProperty;
  3. function processChildren(node, delimeter) {
  4. var list = node.children;
  5. var prev = null;
  6. if (typeof delimeter !== 'function') {
  7. list.forEach(this.node, this);
  8. } else {
  9. list.forEach(function(node) {
  10. if (prev !== null) {
  11. delimeter.call(this, prev);
  12. }
  13. this.node(node);
  14. prev = node;
  15. }, this);
  16. }
  17. }
  18. module.exports = function createGenerator(config) {
  19. function processNode(node) {
  20. if (hasOwnProperty.call(types, node.type)) {
  21. types[node.type].call(this, node);
  22. } else {
  23. throw new Error('Unknown node type: ' + node.type);
  24. }
  25. }
  26. var types = {};
  27. if (config.node) {
  28. for (var name in config.node) {
  29. types[name] = config.node[name].generate;
  30. }
  31. }
  32. return function(node, options) {
  33. var buffer = '';
  34. var handlers = {
  35. children: processChildren,
  36. node: processNode,
  37. chunk: function(chunk) {
  38. buffer += chunk;
  39. },
  40. result: function() {
  41. return buffer;
  42. }
  43. };
  44. if (options) {
  45. if (typeof options.decorator === 'function') {
  46. handlers = options.decorator(handlers);
  47. }
  48. if (options.sourceMap) {
  49. handlers = sourceMap(handlers);
  50. }
  51. }
  52. handlers.node(node);
  53. return handlers.result();
  54. };
  55. };