Skip to content

Instantly share code, notes, and snippets.

@deniskyashif
Created August 17, 2020 10:43
Show Gist options
  • Save deniskyashif/24c055ec845dce9e33344e0afc6dd7ec to your computer and use it in GitHub Desktop.
Save deniskyashif/24c055ec845dce9e33344e0afc6dd7ec to your computer and use it in GitHub Desktop.
/*
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