create.js 1.6 KB

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