Skip to content

Commit

Permalink
add Parsimmon.alt for more efficient .or() chaining
Browse files Browse the repository at this point in the history
  • Loading branch information
jneen committed Feb 3, 2014
1 parent 2078914 commit 9e0848b
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 16 deletions.
17 changes: 9 additions & 8 deletions examples/json.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down
21 changes: 13 additions & 8 deletions src/parsimmon.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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);
Expand Down

0 comments on commit 9e0848b

Please sign in to comment.