Make stringOf() take a callback instead of an array of accepted values

THe `a.stringOf(' \r\n\t'.split('')),` pattern works fine for small sets
of characters, but is horrible for situations like "any alphanumeric".
Instead, let's make it take a callback function that is run on each
character.
This commit is contained in:
Sam Atkins
2024-05-24 15:57:59 +01:00
parent d3dff8c20e
commit 7fccf79591
2 changed files with 6 additions and 6 deletions
@@ -23,12 +23,12 @@ export class Literal extends Parser {
}
/**
* Parses a string composed of the given values.
* @param values An array of strings that will be parsed as the result.
* Parses matching characters as a string.
* @param test Function that takes a character, and returns whether to include it.
*/
export class StringOf extends Parser {
_create (values) {
this.values = values;
_create (test) {
this.test = test;
}
_parse (stream) {
@@ -38,7 +38,7 @@ export class StringOf extends Parser {
while (true) {
let { done, value } = subStream.look();
if ( done ) break;
if ( ! this.values.includes(value) ) break;
if ( ! this.test(value) ) break;
subStream.next();
text += value;
@@ -232,7 +232,7 @@ export default {
number: a => new NumberParser(),
string: a => new StringParser(),
whitespace: a => a.optional(
a.stringOf(' \r\n\t'.split('')),
a.stringOf(c => ' \r\n\t'.includes(c)),
),
}, {
element: it => it[0].value,