Skip to content

Commit ee6d1f6

Browse files
committed
Add a parse utility for consuming an entire input string
It seems nice to provide a function for this rather than making users handle it themselves.
1 parent 33f2f3c commit ee6d1f6

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

src/index.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import * as combinators from './combinators.js'
22
import * as constructors from './constructors.js'
3+
import * as parser from './parser.js'
34

4-
const parsing = { ...combinators, ...constructors }
5+
const parsing = { ...combinators, ...constructors, ...parser }
56
export default parsing
67

78
export * from './combinators.js'

src/parser.ts

+21
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { Either, Right } from '@matt.kantor/either'
2+
import * as either from '@matt.kantor/either'
23

34
export type InvalidInputError = {
45
readonly input: string
@@ -17,3 +18,23 @@ export type Success<Output> = {
1718
readonly remainingInput: string
1819
readonly output: Output
1920
}
21+
22+
/**
23+
* Apply `parser` to the given `input`, requiring it to consume the entire input
24+
* (all the way to the end of the string).
25+
*
26+
* Unlike `Parser`s, in the return value `Output` is not wrapped in `Success`
27+
* (there will never be any `remainingInput`).
28+
*/
29+
export const parse = <Output>(
30+
parser: Parser<Output>,
31+
input: string,
32+
): Either<InvalidInputError, Output> =>
33+
either.flatMap(parser(input), ({ remainingInput, output }) =>
34+
remainingInput.length !== 0
35+
? either.makeLeft({
36+
input,
37+
message: 'excess content followed valid input',
38+
})
39+
: either.makeRight(output),
40+
)

0 commit comments

Comments
 (0)