Tim van der Lippe | 706ec96 | 2021-06-04 13:24:42 +0100 | [diff] [blame] | 1 | var noop = function() {}; |
| 2 | |
| 3 | function ensureFunction(value) { |
| 4 | return typeof value === 'function' ? value : noop; |
| 5 | } |
| 6 | |
| 7 | module.exports = function(node, options, context) { |
| 8 | function walk(node) { |
| 9 | enter.call(context, node); |
| 10 | |
| 11 | switch (node.type) { |
| 12 | case 'Group': |
| 13 | node.terms.forEach(walk); |
| 14 | break; |
| 15 | |
| 16 | case 'Multiplier': |
| 17 | walk(node.term); |
| 18 | break; |
| 19 | |
| 20 | case 'Type': |
| 21 | case 'Property': |
| 22 | case 'Keyword': |
| 23 | case 'AtKeyword': |
| 24 | case 'Function': |
| 25 | case 'String': |
| 26 | case 'Token': |
| 27 | case 'Comma': |
| 28 | break; |
| 29 | |
| 30 | default: |
| 31 | throw new Error('Unknown type: ' + node.type); |
| 32 | } |
| 33 | |
| 34 | leave.call(context, node); |
| 35 | } |
| 36 | |
| 37 | var enter = noop; |
| 38 | var leave = noop; |
| 39 | |
| 40 | if (typeof options === 'function') { |
| 41 | enter = options; |
| 42 | } else if (options) { |
| 43 | enter = ensureFunction(options.enter); |
| 44 | leave = ensureFunction(options.leave); |
| 45 | } |
| 46 | |
| 47 | if (enter === noop && leave === noop) { |
| 48 | throw new Error('Neither `enter` nor `leave` walker handler is set or both aren\'t a function'); |
| 49 | } |
| 50 | |
| 51 | walk(node, context); |
| 52 | }; |