From 3b8f248e2715246706749a85538a5207134195d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Lichtenth=C3=A4ler?= Date: Sun, 7 Aug 2022 20:28:44 +0200 Subject: [PATCH] feat: introduce generic parsers #123 --- src/LikeParser.ts | 2 +- src/Parser.ts | 11 +++++------ src/ParserState.ts | 26 +++++++++++++------------- 3 files changed, 19 insertions(+), 20 deletions(-) diff --git a/src/LikeParser.ts b/src/LikeParser.ts index 00e9cb4..d8fd5f5 100644 --- a/src/LikeParser.ts +++ b/src/LikeParser.ts @@ -1,3 +1,3 @@ import { ParserState } from "./ParserState"; -export type LikeParser = (state: ParserState) => ParserState; +export type LikeParser = (state: ParserState) => ParserState; diff --git a/src/Parser.ts b/src/Parser.ts index bffb532..358137b 100644 --- a/src/Parser.ts +++ b/src/Parser.ts @@ -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

{ + transformState: LikeParser

; - constructor(stateTransformer: LikeParser) { + constructor(stateTransformer: LikeParser

) { this.transformState = stateTransformer; } @@ -18,8 +17,8 @@ export class Parser { }); } - map(callback: (parserState: ParserState) => ParserStateResult) { - return new Parser(parserState => { + map(callback: (parserState: ParserState

) => P) { + return new Parser

(parserState => { const nextState = this.transformState(parserState); return updateParserResult(nextState, callback(nextState)); }); diff --git a/src/ParserState.ts b/src/ParserState.ts index 674cc70..77ab87d 100644 --- a/src/ParserState.ts +++ b/src/ParserState.ts @@ -1,37 +1,37 @@ import { ParserStateResult } from "./ParserStateResult"; -export type ParserState = { +export type ParserState = { 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 = ( + state: ParserState, offset: number, - result: ParserStateResult, -): ParserState => ({ + result: R, +): ParserState => ({ ...state, offset, result, }); -export const updateParserResult = ( - state: ParserState, - result: ParserStateResult, -): ParserState => ({ +export const updateParserResult = ( + state: ParserState, + result: R, +): ParserState => ({ ...state, result, }); -export const updateParserError = ( - state: ParserState, +export const updateParserError = ( + state: ParserState, errorMessage: string, -): ParserState => ({ +): ParserState => ({ ...state, isError: true, errorMessage,