-
Notifications
You must be signed in to change notification settings - Fork 0
/
tokenizer.ts
36 lines (35 loc) · 950 Bytes
/
tokenizer.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
export const openListDelimiters = ['(', '[']
export const closeListDelimiters = [')', ']']
export const listDelimiters = [
...openListDelimiters,
...closeListDelimiters,
]
export const stopChars = [...listDelimiters, ' ', '\n', '\t']
export const avoidChars = [' ', '\n', '\t']
export const stringDelimiters = [`'`, '"']
export const tokenize = code => {
let tokens = []
let chars = code.split('')
let token = ''
let stringFlag = false
for (let i = 0, char; char = chars[i]; i++) {
if (stringFlag || stopChars.indexOf(char) === -1) {
if (stringDelimiters.indexOf(char) !== -1) {
stringFlag = !stringFlag
}
if (stringFlag || avoidChars.indexOf(char) === -1) {
token += char
}
} else {
if (token !== '') {
tokens.push(token)
}
if (avoidChars.indexOf(char) === -1) {
tokens.push(char)
}
token = ''
}
}
tokens = tokens
return tokens
}