javascriptstringalgorithmparsinglexer

Multiline inputs are not possible through code


I have a simple converting script between a custom language and JS

function lexer(code) {
  // lexes code into parts
  const codeParts = [];
  const regex = /"(.*?)"/g; // quote split regex

  const tokens = code.split(regex);

  for (const token of tokens) {
    codeParts.push(token);
  }

  return codeParts;
}
function parse(input) {
  text = input;
  text = text.replace("new", "let");
  text = text.replace("is", "=");
  text = text.replace("say", "console.log");
  text = text.replace("shout", "alert");
  return text;
}
function out(arr) {
  let code = ``;
  for (let i = 0; i < arr.length; i++) {
    if (i % 2 === 0) {
      code = code + parse(arr[i]) + '\n';
    }
    if (i % 2 === 1) {
      code = code + '"' + parse(arr[i]) + '"';
    }
  }
  return code;
}
function convert(input) {
  const codeLex = lexer(input);
  const code = out(codeLex);
  return code;
}
function update(){
    code = '`'+document.getElementById("sparkText").value+'`';
    jsCode = convert(code);
    document.getElementById("jsText").innerHTML = jsCode.substring(1, jsCode.length-2);
}

However, It cant take multiple lines of code, what changes would I have to make for a multiline input and output?

Example

lang 1:

new dog is "dog"
new cat is "cat"

js: let dog = "dog" let cat = "cat"


Solution

  • You can take input from textarea which will allow you for next line (\n) and I think rest below code will do your job

    function lexer(code) {
        // lexes code into parts
        const codeParts = [];
        const regex = /"(.*?)"/g; // quote split regex
        const tokens = code.split(regex);
        for (const token of tokens) {
            codeParts.push(token);
        }
        return codeParts;
    }
    
    function parse(input) {
        return input.replace("new", "let").replace("is", "=").replace("say", "console.log").replace("shout", "alert");
    }
    function out(arr) {
        let code = ``;
        for (let i = 0; i < arr.length; i++)
            code += i % 2 === 0 ? parse(arr[i]) : '"' + parse(arr[i]) + '"';
        return code;
    }
    
    const input = `new dog is "dog"
    new rat is "rat"
    new cat is "cat"`
    
    
    function convertor(input) {
        let output = ``;
        const regex = /\r?\n/; // next line split regex
        const inputs = input.split(regex);
        inputs.forEach(input => {
            output += out(lexer(input)) + "\n"
        });
        return output
    }
    
    console.log(convertor(input));