walk.js 1.2 KB

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