Last active
October 13, 2018 22:50
-
-
Save stevekinney/c195e6bff47b3f0c99de46f5f5020385 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
const example = `22 + 23`; | |
const isWhitespace = character => /\s/.test(character); | |
const isNumber = character => /[0-9]/.test(character); | |
const isOperator = character => /[\+\-\*\/]/.test(character); | |
const tokenize = (input) => { | |
let cursor = 0; | |
const tokens = []; | |
while (cursor < input.length) { | |
const character = input[cursor]; | |
if (isNumber(character)) { | |
let value = character; | |
while (isNumber(input[++cursor])) { | |
value += input[cursor]; | |
} | |
tokens.push({ | |
type: 'Number', | |
value, | |
}); | |
continue; | |
} | |
if (isOperator(character)) { | |
tokens.push({ | |
type: 'Operator', | |
value: character, | |
}); | |
cursor++; | |
continue; | |
} | |
if (isWhitespace(character)) { | |
cursor++; | |
continue; | |
} | |
throw new TypeError(`Unknown character type: "${character}".`); | |
} | |
return tokens; | |
}; | |
console.log(tokenize(example)); |
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
const example = `2 + 2`; | |
const isWhitespace = character => /\s/.test(character); | |
const isNumber = character => /[0-9]/.test(character); | |
const isOperator = character => /[\+\-\*\/]/.test(character); | |
const tokenize = (input) => { | |
let cursor = 0; | |
const tokens = []; | |
while (cursor < input.length) { | |
const character = input[cursor]; | |
if (isNumber(character)) { | |
tokens.push({ | |
type: 'Number', | |
value: +character, | |
}); | |
cursor++; | |
continue; | |
} | |
if (isOperator(character)) { | |
tokens.push({ | |
type: 'Operator', | |
value: character, | |
}); | |
cursor++; | |
continue; | |
} | |
if (isWhitespace(character)) { | |
cursor++; | |
continue; | |
} | |
throw new TypeError(`Unknown character type: "${character}".`); | |
} | |
return tokens; | |
}; | |
console.log(tokenize(example)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment