first
first(p: Parser, m?: string): Parser
Applies a parser and returns the first element of the resulting array.
This parser works only if p returns an array, and it returns the first element of that array. It's most useful with parsers like seq and many that always return arrays, though it will work with parsers like map and always if they are programmed to return arrays.
first(p) is an optimized implementation of chain(p, x => always(x[0])).
Example
const parser = first(many1(any()))
const s = parse(parser, '12345')
console.log(status(s)) // "ok"
console.log(success(s)) // "1"
const f = parse(parser, '')
console.log(status(f)) // "fail"
console.log(failure(f)) // Parse error at (line 1, column 1):
//
//
// ^
// Expected any character
// Note: failure occurred at the end of input
Parameters
p: The parser to apply. This parser should return an array.m: The optional expected error message that will take the place of the default error message.
Success
- Succeeds if
psucceeds. Returns the first element of the array thatpreturns. If there is not at least one element in that array, it will returnundefinedin the same manner thatundefinedis always returned when indexing a non-existent element of an array.
Failure
- Fails if
pfails.
Fatal Failure
- Fails fatally if
pfails fatally.
Throws
- Throws an error if
pis not a parser. - Throws an error if
mexists and is not a string. - Throws an error if
psucceeds but does not return an array.