Created
October 3, 2018 01:53
-
-
Save huytd/c9badacd4d534943b3525ac3922a9271 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as fs from 'fs'; | |
import { parse } from 'querystring'; | |
const data = fs.readFileSync('./research.org', 'utf-8'); | |
interface Token { | |
success: boolean; | |
value?: string; | |
rest?: string; | |
data?: string; | |
error?: Error; | |
}; | |
interface ParserFn { | |
(input?: string): Token; | |
}; | |
const match_char = (c: string): ParserFn => (input: string): Token => { | |
if (input[0] === c) { | |
return <Token>{ | |
success: true, | |
value: input[0], | |
rest: input.slice(1), | |
data: null, | |
error: null | |
}; | |
} | |
throw new Error(`MatchCharError: Expected ${c}, found ${input[0]}`); | |
}; | |
const match_any_char_to_eol = (): ParserFn => (input: string): Token => { | |
let parsed: string = ""; | |
while (input[0] != "\n" && input.length) { | |
console.log(input); | |
parsed += input[0]; | |
input = input.slice(1); | |
} | |
return <Token>{ | |
success: true, | |
value: parsed, | |
rest: input, | |
data: null, | |
error: null | |
}; | |
}; | |
const combine_parser = (parsers: ParserFn[]): ParserFn => (input: string): Token => { | |
let next = input; | |
let result = []; | |
for (let i = 0; i < parsers.length; i++) { | |
const parser: ParserFn = parsers[i]; | |
const parse_result: Token = parser(next); | |
result.push(parse_result.value); | |
next = parse_result.rest; | |
} | |
return <Token>{ | |
success: true, | |
value: result.join(''), | |
rest: next, | |
data: null, | |
error: null | |
}; | |
}; | |
let input = "*** Header"; | |
console.log(combine_parser([match_char('*'), match_char('*'), match_char('*'), match_any_char_to_eol()])(input)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment