From 10d7a6aded0f212a978906ea720cb18e4ec4017d Mon Sep 17 00:00:00 2001 From: David Majda Date: Fri, 9 Oct 2015 16:34:19 +0200 Subject: [PATCH] Simplify the arithmetics example grammar The arithmetics example grammar is the first thing everyone sees in the online editor at the PEG.js website, but it begins with a complicated |combine| function in the initializer. Without understanding it it is impossible to understand code in the actions. This may be a barrier to learning how PEG.js works. This commit removes the |combine| function and gets rid of the whole initializer, removing the learning obstacle and streamlining action code. The only cost is a slight code duplication. --- examples/arithmetics.pegjs | 36 ++++++++++++++++-------------------- 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/examples/arithmetics.pegjs b/examples/arithmetics.pegjs index 597f7d4..2cc2a76 100644 --- a/examples/arithmetics.pegjs +++ b/examples/arithmetics.pegjs @@ -5,32 +5,28 @@ * Accepts expressions like "2 * (3 + 4)" and computes their value. */ -{ - function combine(first, rest, combiners) { - var result = first, i; - - for (i = 0; i < rest.length; i++) { - result = combiners[rest[i][1]](result, rest[i][3]); - } - - return result; - } -} - Expression = first:Term rest:(_ ("+" / "-") _ Term)* { - return combine(first, rest, { - "+": function(left, right) { return left + right; }, - "-": function(left, right) { return left - right; } - }); + var result = first, i; + + for (i = 0; i < rest.length; i++) { + if (rest[i][1] === "+") { result += rest[i][3]; } + if (rest[i][1] === "-") { result -= rest[i][3]; } + } + + return result; } Term = first:Factor rest:(_ ("*" / "/") _ Factor)* { - return combine(first, rest, { - "*": function(left, right) { return left * right; }, - "/": function(left, right) { return left / right; } - }); + var result = first, i; + + for (i = 0; i < rest.length; i++) { + if (rest[i][1] === "*") { result *= rest[i][3]; } + if (rest[i][1] === "/") { result /= rest[i][3]; } + } + + return result; } Factor