Last active
February 13, 2020 06:00
-
-
Save sgentle/e65cb8eeaaf5a21fb3b644446fcdfee9 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
const TOKENS = { | |
id: /[a-z]+/, | |
num: /(?:[0-9]+\.)?[0-9]+/, | |
op: /[+-/*]/, | |
leftparen: /\(/, | |
rightparen: /\)/, | |
error: /./ | |
} | |
function* tokenize(str, tokens) { | |
const names = Object.keys(tokens) | |
const pattern = Object.values(tokens).map(x => `(${x.source})`).join('|') | |
const re = new RegExp(pattern, 'g') | |
let match; | |
while (match = re.exec(str)) { | |
for (let i = 1; i < match.length; i++) { | |
if (match[i] !== undefined) { | |
yield {type: names[i-1], content: match[i], index: match.index} | |
break | |
} | |
} | |
} | |
} | |
for (const token of tokenize('-123+abc(456.78*9)', TOKENS)) { | |
console.log(token) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment