Created
March 8, 2016 22:22
-
-
Save assertchris/9bc8fa85d694be22004e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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