I'm currently trying to add simple Math solving capability's to my discord bot, which is done by first sterilizing user input (to fix security issues), then running it via new Function
. The issue is that I would like all the functions currently inside the Math
object to be stand alone for the user, heres what I mean:
To get the square root of a number, inside of JS I could use Math.sqrt(25)
. I don't want the user to have to deal with the Math.
, so ideally they would just use sqrt(25)
. The total message might look something like: !solve sqrt(25)
, which would return 5.
Because the message content is already a string, and has been sterilized, the only things in this string would be: numbers, operations (+, -, *, /, ^ or **), or mathematical functions (cos, sin, sqrt, etc.). Because these mathematical functions are the only "words" in here, a really simple way around this issue is to just take all the "words" in this string, add Math.
before each one, and then solve the equation.
Here is the psudo code and example:
Psudocode: | Example:
1. Get user input | input = '! solve 5 + cos(10) / sqrt(50)*random()'
2. Trim input to only the equation | input = '5 + cos(10) / sqrt(50)*random()'
3. Add Math. to beginning of words | input = '5 + Math.cos(10) / Math.sqrt(50)*Math.random()'
4. Compile into result variable | result = new Function(`return ${input}`);
5. If step 4 failed, tell user | send(`bla is not a math function`); //<-- if input was bla(50)
6. Send user result | send(result);
I have every step except step 4 worked out, and this is where I need some understanding. I found this PHP- Adding ":" character to all words in string PHP function, which my brain cant seem to understand, and this Regular Expression - Add a character before/after each word notepad answer, which would have worked, except the replacer was a regex itself, which Js' string.replace()
does not accept, confirmed by typescript. Could someone point me in the right direction?