nth
nth(p: Parser, n: number. m?: string): Parser
Applies a parser and returns a given element of the resulting array.
This parser works only if p returns an array, and it returns the nth (0-based) 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.
nth(p, n) is an optimized implementation of chain(p, x => always(x[n])).
Example
const parser = nth(many1(any()), 3)
const s = parse(parser, '12345')
console.log(status(s)) // "ok"
console.log(success(s)) // "4"
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.n: The 0-based index of the element fromp's result that should be returned.m: The optional expected error message that will take the place of the default error message.
Success
- Succeeds if
psucceeds. Returns the element of the array thatpreturns with the indexn. If there are notn + 1elements 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
nis not a number. - Throws an error if
mexists and is not a string. - Throws an error if
psucceeds but does not return an array.