Friday, 24 September 2021

How leetcode do this: Read user's input String as multiple JavaScript functions and run a main function with user's input params

I am trying to replicate what leetcode does, as my React learning project. Below is my current UI setup.

I am using AceEditor as my text editor, right now I can read the value from the editor on change.

I want to execute the function containsDuplicate when I click the Run code button.

What I have right now is a string codeValue represent the user's input in the string format, and the testCase as the functions params in the string format as well,

  // 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); 
  };

What should I do to run the function containsDuplicate with the params testCase ? Assume the function name is always containsDuplicate?

Eval() will run the string as JS function, but what I need is, when the string is just function declaration, and there are multiple function declarations, I need to find the correct function from string, and run that function with give input.

Let's say the input string is

functionA() {
  functionB();
}

functionB() {
}

I need to read that string and run functionA([1,2,3,4])

I don't have a good way to do this right now.

Thanks!

enter image description here



from How leetcode do this: Read user's input String as multiple JavaScript functions and run a main function with user's input params

No comments:

Post a Comment