JSFiddle - React, Tailwind, and code Playground
JavaScript
//Make an enum it's just easier to type this way.
const _types = [
"LEFT_BRACKET",
"RIGHT_BRACKET",
"LEFT_BRACE",
"RIGHT_BRACE",
"TRUE",
"FALSE",
"NULL",
"COMMA",
"STRING",
"COLON",
"QUOTE"
];
const TYPES = {};
_types.forEach((type, index)=>{
TYPES[type] = index;
});
function getString(text, index){
let str = "";
let len = 0;
for(let i = index + 1; i<text.length; i++){
if(text[i] === `"`){
return [str, len];
} else if(text[i] === "\\" && text[i+1] === `"`){
str += `"`;
len +=2;
i++;
} else{
len++;
str += text[i];
}
}
return null;
}
function lex(text) {
let index = 0;
const result = [];
while(index < text.length){
const at = text[index];
switch(at){
case "{":
result.push({type: TYPES.LEFT_BRACE});
index++;
break;
case "}":
result.push({type: TYPES.RIGHT_BRACE});
index++
break;
case ":":
result.push({type: TYPES.COLON});
index++;
break;
case ",":
result.push({type: TYPES.COMMA});
index++;
break;
case "n":
if(text.substring(index, index+4) === "null"){
index+=4
result.push({type: TYPES.NULL});
} else {
throw new Error("unexpected character parsing null");
}
break;
case "f":
if(text.substring(index, index+5) === "false"){
index+=5
result.push({type: TYPES.FALSE});
} else {
throw new Error("unexpected character parsing false");
}
break;
case "t":
if(text.substring(index, index+4) === "true"){
index+=4
result.push({type: TYPES.TRUE});
} else {
console.log(text.substring(index, index+4));
throw new Error("unexpected character parsing true");
}
break;
case "\"":
const str = getString(text, index);
if(str === null){
throw new Error("Expected end of string");
}
result.push({type: TYPES.STRING, value: str[0]});
...