Skip to content

Instantly share code, notes, and snippets.

@assertchris
Created March 8, 2016 22:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save assertchris/9bc8fa85d694be22004e to your computer and use it in GitHub Desktop.
Save assertchris/9bc8fa85d694be22004e to your computer and use it in GitHub Desktop.
class Lexer {
get patterns() {
return {
"whitespace": "\\s+",
"type": "int",
"assign": "=",
"identity": "[a-z]+",
"value": "[0-9]+"
};
}
analyse(code = "") {
let tokens = [];
while(true) {
let length = code.length;
for (let key in this.patterns) {
let pattern = new RegExp(
"^(" + this.patterns[key] + ")"
);
let matches = code.match(pattern);
if (matches) {
tokens.push([
key, matches[1]
]);
code = code.substring(matches[1].length);
}
}
if (length == code.length) {
break;
}
}
return {
tokens,
code,
};
}
}
let lexer = new Lexer();
let result = lexer.analyse("int minutes = 90");
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment