createParser
createParser<
C
>(config
): (opts
) =>ParseResult
<C
>
Creates a parser function based on a given configuration of token options.
The returned parser will:
- Trim and split the input string by whitespace into tokens.
- For each token that matches a key in the config:
- If a
next
parser is provided, consume the following token and parse it.- If parsing yields a non-null value, assign it to the result.
- Otherwise, roll back and optionally apply
default
.
- If no
next
parser, butdefault
is provided, assign the default value.
- If a
- Collect all tokens not matching any config key into
rest
, preserving order.
Type Parameters
Section titled “Type Parameters”C
extends ParserConfig
The shape of the parser configuration.
Parameters
Section titled “Parameters”config
Section titled “config”C
Mapping of token keys to Option definitions.
Returns
Section titled “Returns”A function that parses a string according to the provided config and returns a structured result.
(
opts
):ParseResult
<C
>
Parameters
Section titled “Parameters”string
Returns
Section titled “Returns”ParseResult
<C
>
Example
Section titled “Example”const parse = createParser({ width: { next: t => parseInt(t) || 100 }, bold: { default: true }})const result = parse('foo width 200 bar bold')// result: { width: 200, bold: true, rest: 'foo bar' }