walk.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. 'use strict';
  2. var noop = function() {};
  3. function ensureFunction(value) {
  4. return typeof value === 'function' ? value : noop;
  5. }
  6. module.exports = function(node, options, context) {
  7. function walk(node) {
  8. enter.call(context, node);
  9. switch (node.type) {
  10. case 'Group':
  11. node.terms.forEach(walk);
  12. break;
  13. case 'Multiplier':
  14. walk(node.term);
  15. break;
  16. case 'Type':
  17. case 'Property':
  18. case 'Keyword':
  19. case 'AtKeyword':
  20. case 'Function':
  21. case 'String':
  22. case 'Token':
  23. case 'Comma':
  24. break;
  25. default:
  26. throw new Error('Unknown type: ' + node.type);
  27. }
  28. leave.call(context, node);
  29. }
  30. var enter = noop;
  31. var leave = noop;
  32. if (typeof options === 'function') {
  33. enter = options;
  34. } else if (options) {
  35. enter = ensureFunction(options.enter);
  36. leave = ensureFunction(options.leave);
  37. }
  38. if (enter === noop && leave === noop) {
  39. throw new Error('Neither `enter` nor `leave` walker handler is set or both aren\'t a function');
  40. }
  41. walk(node, context);
  42. };