diff --git a/src/checks.js b/src/checks.js index a07abe2..832bd25 100644 --- a/src/checks.js +++ b/src/checks.js @@ -16,7 +16,7 @@ PEG.compiler.checks = [ return function(node) { each(node[propertyName], check); }; } - var checkFunctions = { + var check = buildNodeVisitor({ grammar: function(node) { for (var name in node.rules) { @@ -49,9 +49,7 @@ PEG.compiler.checks = [ literal: nop, any: nop, "class": nop - }; - - function check(node) { checkFunctions[node.type](node); } + }); check(ast); }, @@ -64,7 +62,7 @@ PEG.compiler.checks = [ check(node.expression, appliedRules); } - var checkFunctions = { + var check = buildNodeVisitor({ grammar: function(node, appliedRules) { for (var name in node.rules) { @@ -114,11 +112,7 @@ PEG.compiler.checks = [ literal: nop, any: nop, "class": nop - }; - - function check(node, appliedRules) { - checkFunctions[node.type](node, appliedRules); - } + }); check(ast, []); } diff --git a/src/emitter.js b/src/emitter.js index cfe34f0..c9909f0 100644 --- a/src/emitter.js +++ b/src/emitter.js @@ -90,7 +90,7 @@ PEG.compiler.emitter = function(ast) { } }; - var emitFunctions = { + var emit = buildNodeVisitor({ grammar: function(node) { var initializerCode = node.initializer !== null ? emit(node.initializer) @@ -710,11 +710,7 @@ PEG.compiler.emitter = function(ast) { } ); } - }; - - function emit(node, resultVar) { - return emitFunctions[node.type](node, resultVar); - } + }); return emit(ast); }; diff --git a/src/passes.js b/src/passes.js index ff5efc0..c496ff4 100644 --- a/src/passes.js +++ b/src/passes.js @@ -28,7 +28,7 @@ PEG.compiler.passes = [ }; } - var replaceFunctions = { + var replace = buildNodeVisitor({ grammar: function(node, from, to) { for (var name in node.rules) { @@ -59,11 +59,7 @@ PEG.compiler.passes = [ literal: nop, any: nop, "class": nop - }; - - function replace(node, from, to) { - replaceFunctions[node.type](node, from, to); - } + }); replace(ast, from, to); } diff --git a/src/utils.js b/src/utils.js index 9c80d82..256b2ec 100644 --- a/src/utils.js +++ b/src/utils.js @@ -73,3 +73,15 @@ function quoteForRegexpClass(s) { .replace(/\u2029/g, '\\u2029') // paragraph separator .replace(/\n/g, '\\n') // line feed } + +/* + * Builds a node visitor -- a function which takes a node and any number of + * other parameters, calls an appropriate function according to the node type, + * passes it all its parameters and returns its value. The functions for various + * node types are passed in a parameter to |buildNodeVisitor| as a hash. + */ +function buildNodeVisitor(functions) { + return function(node) { + functions[node.type].apply(null, arguments)); + } +}