Created
May 20, 2018 10:09
-
-
Save sidoshi/fa818ea856502542751ab5f9d6fea7f8 to your computer and use it in GitHub Desktop.
A parser for tree syntax
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
// const input = | |
// '(2 (7 (2 () ()) (6 (5 () ()) (11 () ()))) (5 () (9 (4 () ()) ())))' | |
const tokenizer = input => { | |
let current = 0 | |
const tokens = [] | |
while (current < input.length) { | |
let char = input[current] | |
if (char === '(' || char === ')') { | |
tokens.push({ | |
type: 'paren', | |
value: char, | |
}) | |
current += 1 | |
continue | |
} | |
const WHITESPACE = /\s/ | |
if (WHITESPACE.test(char)) { | |
current += 1 | |
continue | |
} | |
const NUMBERS = /[0-9]/ | |
if (NUMBERS.test(char)) { | |
let value = '' | |
while (NUMBERS.test(char)) { | |
value += char | |
current += 1 | |
char = input[current] | |
} | |
tokens.push({ | |
type: 'number', | |
value: +value, | |
}) | |
continue | |
} | |
throw new Error(`Invalid Syntax: ${char} at ${current}`) | |
} | |
return tokens | |
} | |
const parseNode = tokens => { | |
let token = tokens.shift() | |
console.log(token, tokens) | |
if (token.type === 'number') { | |
return token.value | |
} | |
if (token.type === 'paren' && token.value === '(') { | |
if (tokens[0].type === 'paren' && tokens[0].value === ')') { | |
tokens.shift() | |
return null | |
} | |
const node = { | |
element: parseNode(tokens), | |
left: parseNode(tokens), | |
right: parseNode(tokens), | |
} | |
tokens.shift() | |
return node | |
} | |
} | |
// console.log(parseNode(tokenizer(input)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment