Created
August 17, 2020 10:43
-
-
Save deniskyashif/24c055ec845dce9e33344e0afc6dd7ec 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
/* | |
S -> aAe | |
A -> bAd | c | |
*/ | |
const parse = (() => { | |
let tokens; | |
let pos = 0; | |
const peek = () => tokens[pos]; | |
const eat = token => { | |
if (peek() !== token) | |
throw `Invalid token ${peek()}. Expected ${token}`; | |
pos++; | |
}; | |
function S() { | |
eat('a'); | |
A(); | |
eat('e'); | |
} | |
function A() { | |
if (peek() === 'b') { | |
eat('b'); | |
A(); | |
eat('d'); | |
} else { | |
eat('c'); | |
} | |
} | |
return input => { | |
tokens = input; | |
pos = 0; | |
try { | |
S(); | |
return true; | |
} catch (err) { | |
console.log(err); | |
return false; | |
} | |
}; | |
})(); | |
console.log(parse('abcde')); | |
console.log(parse('ace')); | |
console.log(parse('abbbbcdddde')); | |
console.log(parse('abbcdde')); | |
console.log(parse('abbcde')); | |
console.log(parse('abccde')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment