Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/*
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
You can’t perform that action at this time.