Skip to content

Commit

Permalink
Closes #161 tryAll rather in snippets
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolas-zozol committed Nov 12, 2020
1 parent dfdf395 commit b524a34
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 40 deletions.
26 changes: 25 additions & 1 deletion documentation/flow-bundle.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,4 +110,28 @@ So it logically fails, and unfortunately these types of failures are pretty hard



Moreover repeating an optional repeat can cause never-ending running code: https://github.com/d-plaindoux/masala-parser/issues/81
Moreover repeating an optional repeat can cause never-ending running code: https://github.com/d-plaindoux/masala-parser/issues/81


F.try().or()
----

Masala is a low level library. It's up to you to mix these functions. It's very common for some kind
of job to mix `F.try(x).or(F.try(y)).or(z)`

A useful snippet is this `tryAll` function

```javascript
function tryAll(array){
if (array.length === 0){
return F.nop();
}
let parser = F.try(array[0]);
for (let i=1; i < array.length; i++){
parser = parser.or(F.try(array[i]));
}

return parser;
}
```

16 changes: 1 addition & 15 deletions src/lib/parsec/flow-bundle.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,19 +75,6 @@ function doTry(p) {
);
}


function tryAll(array){
if (array.length === 0){
return nop();
}
let parser = doTry(array[0]);
for (let i=1; i < array.length; i++){
parser = parser.or(doTry(array[i]));
}

return parser;
}

function layer(p) {
return new Parser((input, index = 0) =>
p
Expand Down Expand Up @@ -172,8 +159,7 @@ export default {
satisfy,
startWith,
moveUntil,
dropTo,
tryAll
dropTo
};

/**Optimization functions */
Expand Down
25 changes: 1 addition & 24 deletions src/test/parsec/flow-bundle-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -331,29 +331,6 @@ export default {

test.equals(value.join(''), 'ababa');
test.done();
},
'expect chaining tries':function(test){

const p1 = C.char('1');
const p2 = C.string('22');
const p3 = C.string('33');
const parser = C.string("start").then(
F.tryAll([p1,p2,p3])
);

// should fail
let response = parser.parse(stream.ofString("start3"));
test.equal(response.isAccepted(), false)
test.equal(response.offset, 5);


// should succeed
response = parser.parse(stream.ofString("start22"));
test.equal(response.isAccepted(), true)
test.equal(response.offset, 7);

test.done()

},
}
};

0 comments on commit b524a34

Please sign in to comment.