我正在尝试复制 leetcode 的功能,作为我的 React 学习项目。以下是我当前的 UI 设置。
我正在使用 AceEditor 作为我的文本编辑器,现在我可以从编辑器中读取更改时的值。
我想在单击 Run code
按钮时执行函数 containsDuplicate
。
我现在有一个字符串 codeValue
以字符串格式表示用户的输入,以及 testCase
作为字符串格式的函数参数,
// the codeValue is the complete text in the Ace Editor are
const [codeValue, setCodeValue] = useState('');
// The testCase is [1,2,3,1] which reads from the TestCase section
const [testCase, setTextCaseValue] = useState('');
const submitHandler = (inputParams) => {
console.log(codeValue);
};
我应该怎么做才能使用参数 testCase
运行函数 containsDuplicate
?假设函数名总是containsDuplicate
?
Eval() 会将字符串作为 JS 函数运行,但我需要的是,当字符串只是函数声明,并且有多个函数声明时,我需要从字符串中找到正确的函数,然后运行该函数提供意见。
假设输入字符串是
functionA() {
functionB();
}
functionB() {
}
我需要读取该字符串并运行 functionA([1,2,3,4])
我现在没有好的方法来做到这一点。
谢谢!
最佳答案
如果函数名称是固定的*,您可以通过将用户代码包装到另一个函数中来“提取”正确的函数,然后简单地从中返回
该函数:
const codeInput = `
function foo() {
console.log('foo');
}
function containsDuplicate(input) {
foo();
console.log('input', input);
return 42;
}
`;
const code = new Function(codeInput + '; return containsDuplicate;')()
const result = code([1,2,3]);
console.log('result', result);
您还可以添加额外的逻辑,在尝试返回之前验证 containsDuplicate
是否存在。
如果您不想口授函数名称,有几个或多或少复杂的解决方案:
module.exports
。eval
/new Function
它)(可能还有更轻的解决方案将 ES 模块语法转换为例如 IIFE)。*:这是制作 IMO 的合理假设。由于它是一个特殊用途的环境,您可以指定代码的结构并要求必须有一个具有特定名称的函数。
关于javascript - leetcode 如何做到这一点 : Read user's input String as multiple JavaScript functions and run a main function with user's input params,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69250338/