Skip to content

createParser

createParser<C>(config): (opts) => ParseResult<C>

Creates a parser function based on a given configuration of token options.

The returned parser will:

  1. Trim and split the input string by whitespace into tokens.
  2. 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, but default is provided, assign the default value.
  3. Collect all tokens not matching any config key into rest, preserving order.

C extends ParserConfig

The shape of the parser configuration.

C

Mapping of token keys to Option definitions.

A function that parses a string according to the provided config and returns a structured result.

(opts): ParseResult<C>

string

ParseResult<C>

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' }