Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

add Parsimmon.alt for more efficient .or() chaining

  • Loading branch information...
commit 9e0848bd7b26ed128bcc8666d8ec2d301e00a52b 1 parent 2078914
@jneen authored
Showing with 22 additions and 16 deletions.
  1. +9 −8 examples/json.js
  2. +13 −8 src/parsimmon.js
View
17 examples/json.js
@@ -7,14 +7,15 @@ var lazy = Parsimmon.lazy;
var json = (function() {
var json = lazy(function() {
- return object
- .or(array)
- .or(stringLiteral)
- .or(numberLiteral)
- .or(nullLiteral)
- .or(trueLiteral)
- .or(falseLiteral)
- .skip(regex(/^\s*/m));
+ return alt([
+ object,
+ array,
+ stringLiteral,
+ numberLiteral,
+ nullLiteral,
+ trueLiteral,
+ falseLiteral
+ ]).skip(regex(/^\s*/m));
});
var escapes = {
View
21 src/parsimmon.js
@@ -68,13 +68,7 @@ Parsimmon.Parser = P(function(_, _super, Parser) {
// -*- primitive combinators -*- //
_.or = function(alternative) {
- var self = this;
-
- return Parser(function(stream, i) {
- var result = self._(stream, i);
-
- return result.status ? result : furthestBacktrackFor(alternative._(stream, i), result);
- });
+ return alt([this, alternative]);
};
_.then = function(next) {
@@ -303,7 +297,18 @@ Parsimmon.Parser = P(function(_, _super, Parser) {
return furthestBacktrackFor(makeSuccess(i, accum), result);
});
- }
+ };
+
+ var alt = Parsimmon.alt = function(parsers) {
+ return Parser(function(stream, i) {
+ var result;
+ for (var j = 0; j < parsers.length; j += 1) {
+ result = furthestBacktrackFor(parsers[j]._(stream, i), result);
+ if (result.status) return result;
+ }
+ return result;
+ });
+ };
var index = Parsimmon.index = Parser(function(stream, i) {
return makeSuccess(i, i);
Please sign in to comment.
Something went wrong with that request. Please try again.