walk.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. const noop = function() {};
  2. function ensureFunction(value) {
  3. return typeof value === 'function' ? value : noop;
  4. }
  5. export function walk(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. case 'Boolean':
  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. let enter = noop;
  31. let 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. };