From 6bbd88088b831472a27ac90d9cff79e8dd798f30 Mon Sep 17 00:00:00 2001 From: David Majda Date: Fri, 19 Mar 2010 10:38:46 +0100 Subject: [PATCH] Implemented and used PEG.ArrayUtils.each. --- lib/metagrammar.js | 2 +- lib/metagrammar.pegjs | 2 +- lib/runtime.js | 7 +++++++ test/runtime-test.js | 13 +++++++++++++ 4 files changed, 22 insertions(+), 2 deletions(-) diff --git a/lib/metagrammar.js b/lib/metagrammar.js index 7f8b6c5..490620b 100644 --- a/lib/metagrammar.js +++ b/lib/metagrammar.js @@ -54,7 +54,7 @@ PEG.grammarParser = (function(){ var result0 = result1 !== null ? (function() { var result = {}; - for (var i = 0; i < (arguments[1]).length; i++) { result[(arguments[1])[i].getName()] = (arguments[1])[i]; } + PEG.ArrayUtils.each((arguments[1]), function(rule) { result[rule.getName()] = rule; }); return result; }).apply(this, result1) : null; diff --git a/lib/metagrammar.pegjs b/lib/metagrammar.pegjs index 47d4229..033f596 100644 --- a/lib/metagrammar.pegjs +++ b/lib/metagrammar.pegjs @@ -1,6 +1,6 @@ grammar: __ rule+ { var result = {}; - for (var i = 0; i < $2.length; i++) { result[$2[i].getName()] = $2[i]; } + PEG.ArrayUtils.each($2, function(rule) { result[rule.getName()] = rule; }); return result; } diff --git a/lib/runtime.js b/lib/runtime.js index 058b766..61c889d 100644 --- a/lib/runtime.js +++ b/lib/runtime.js @@ -13,6 +13,13 @@ PEG = {}; /* Array manipulation utility functions. */ PEG.ArrayUtils = { + each: function(array, callback) { + var length = array.length; + for (var i = 0; i < length; i++) { + callback(array[i]); + } + }, + map: function(array, callback) { var result = []; var length = array.length; diff --git a/test/runtime-test.js b/test/runtime-test.js index 263f1d3..9a7a469 100644 --- a/test/runtime-test.js +++ b/test/runtime-test.js @@ -4,6 +4,19 @@ module("PEG.ArrayUtils"); +test("each", function() { + var sum; + function increment(x) { sum += x; } + + sum = 0; + PEG.ArrayUtils.each([], increment); + strictEqual(sum, 0); + + sum = 0; + PEG.ArrayUtils.each([1, 2, 3], increment); + strictEqual(sum, 6); +}); + test("map", function() { function square(x) { return x * x; }