From b16be42e6dc51e6333372d3d92d10ffd6bb955d2 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Thu, 15 Dec 2016 13:39:51 -0800 Subject: [PATCH] Add `fallback` and simplify `or` --- parsimmon/index.d.ts | 15 +++++++++------ parsimmon/parsimmon-tests.ts | 5 ++++- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/parsimmon/index.d.ts b/parsimmon/index.d.ts index 85ea74cfd9..417cd962b5 100644 --- a/parsimmon/index.d.ts +++ b/parsimmon/index.d.ts @@ -83,8 +83,7 @@ declare namespace Parsimmon { /** * returns a new parser which tries parser, and if it fails uses otherParser. */ - or(otherParser: Parser): Parser; - or(otherParser: Parser): Parser; + or(otherParser: Parser): Parser; /** * returns a new parser which tries parser, and on success calls the given function * with the result of the parse, which is expected to return another parser, which @@ -106,14 +105,18 @@ declare namespace Parsimmon { * transforms the output of parser with the given function. */ map(call: (result: T) => U): Parser; - /** - * expects otherParser after parser, but preserves the yield value of parser. - */ - skip(otherParser: Parser): Parser; /** * returns a new parser with the same behavior, but which yields aResult. */ result(aResult: U): Parser; + /** + * returns a new parser that returns the fallback value if the first parser failed. + */ + fallback(fallbackValue: U): Parser; + /** + * expects otherParser after parser, but preserves the yield value of parser. + */ + skip(otherParser: Parser): Parser; /** * expects parser zero or more times, and yields an array of the results. */ diff --git a/parsimmon/parsimmon-tests.ts b/parsimmon/parsimmon-tests.ts index e0c6e0b00c..6be7eb307a 100644 --- a/parsimmon/parsimmon-tests.ts +++ b/parsimmon/parsimmon-tests.ts @@ -38,6 +38,7 @@ var indexPar: Parser; var fooPar: Parser; var barPar: Parser; +var fooOrBarPar: Parser; // -- -- -- -- -- -- -- -- -- -- -- -- -- @@ -84,7 +85,7 @@ fooResult = fooPar.parse(str); foo = fooPar.tryParse(str); fooPar = fooPar.or(fooPar); -anyPar = fooPar.or(barPar); +fooOrBarPar = fooPar.or(barPar); barPar = fooPar.chain((f) => { foo = f; @@ -108,6 +109,8 @@ fooPar = fooPar.skip(barPar); barPar = barPar = fooPar.result(bar); +fooOrBarPar = fooPar.fallback(bar); + // -- -- -- -- -- -- -- -- -- -- -- -- -- fooArrPar = fooPar.many();