提问人:Vatsa Pandey 提问时间:11/2/2023 更新时间:11/2/2023 访问量:26
无法通过代码进行多行输入
Multiline inputs are not possible through code
问:
我有一个简单的自定义语言和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);
}
但是,它不能采用多行代码,我必须对多行输入和输出进行哪些更改?
例
语言 1:
new dog is "dog"
new cat is "cat"
js:let dog = "dog" let cat = "cat"
答:
2赞
Kamran
11/2/2023
#1
您可以从 textarea 获取输入,这将允许您进行下一行 (\n),我认为下面的代码将完成您的工作
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));
评论