Skip to content

Commit

Permalink
feat: introduce generic parsers
Browse files Browse the repository at this point in the history
  • Loading branch information
Bikossor committed Oct 29, 2022
1 parent ce66eaf commit 3b8f248
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 20 deletions.
2 changes: 1 addition & 1 deletion src/LikeParser.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import { ParserState } from "./ParserState";

export type LikeParser = (state: ParserState) => ParserState;
export type LikeParser<R> = (state: ParserState<R>) => ParserState<R>;
11 changes: 5 additions & 6 deletions src/Parser.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { LikeParser } from "./LikeParser";
import { ParserStateResult } from "./ParserStateResult";
import { ParserState, updateParserResult } from "./ParserState";

export class Parser {
transformState: LikeParser;
export class Parser<P> {
transformState: LikeParser<P>;

constructor(stateTransformer: LikeParser) {
constructor(stateTransformer: LikeParser<P>) {
this.transformState = stateTransformer;
}

Expand All @@ -18,8 +17,8 @@ export class Parser {
});
}

map(callback: (parserState: ParserState) => ParserStateResult) {
return new Parser(parserState => {
map(callback: (parserState: ParserState<P>) => P) {
return new Parser<P>(parserState => {
const nextState = this.transformState(parserState);
return updateParserResult(nextState, callback(nextState));
});
Expand Down
26 changes: 13 additions & 13 deletions src/ParserState.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,37 @@
import { ParserStateResult } from "./ParserStateResult";

export type ParserState = {
export type ParserState<R> = {
offset: number;
input: string;
result: ParserStateResult | null;
result: R | null;
isError: boolean;
errorMessage?: string;
};

//#region ParserState utility functions

export const updateParserState = (
state: ParserState,
export const updateParserState = <R>(
state: ParserState<R>,
offset: number,
result: ParserStateResult,
): ParserState => ({
result: R,
): ParserState<R> => ({
...state,
offset,
result,
});

export const updateParserResult = (
state: ParserState,
result: ParserStateResult,
): ParserState => ({
export const updateParserResult = <R>(
state: ParserState<R>,
result: R,
): ParserState<R> => ({
...state,
result,
});

export const updateParserError = (
state: ParserState,
export const updateParserError = <R>(
state: ParserState<R>,
errorMessage: string,
): ParserState => ({
): ParserState<R> => ({
...state,
isError: true,
errorMessage,
Expand Down

0 comments on commit 3b8f248

Please sign in to comment.