Method for passing a formula to a JS function?

Hi.

I’m working on a project where I’d like to take a custom function from the user, at least ideally via an ‘input text’ box that would be passed to a JS function as a parameter and then return the transformed value.

There would be only a single independent variable (i.e. ‘x’), and the purpose of the text box would be to allow the user to make different transforms to a dataset. For example ‘x^2’, ‘x/100’, etc.

From the MDN docs I found the ‘eval()’ function which I think might suit this purpose though the docs also quickly go on to say how dangerous eval is and basically not to use it.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

I wondered if anyone had any thoughts on how to safely accomplish this ?

The MDN doc goes on to tell you how to do it without eval.

Yeah, using eval, especially when being used for user input is dangerous.

There are JS libraries to parse formulas, like this and this. Find a free one you like or build your own.