-4

I am working with the built in Math library in js, and need a way to call its functions (eg:sin) without using Math. before the function name. Is there a way I can import it (without node) so this could be achieved, such that the following code would be valid? :

var equation = "sin(x)";

eval(equation.replace("x","0")); // Should return 0
Gamaray
  • 68
  • 1
  • 8
  • 4
    You're using `eval` so you may as well use `with` – Jaromanda X Aug 03 '22 at 11:46
  • 1
    @JaromandaX Two evils do not make a right ;) – mplungjan Aug 03 '22 at 11:47
  • 3
    Why are you string-replacing equations in the first place? You should write a function with parameters: `function equation(x) { return Math.sin(x); }`; or, well, `const equation = Math.sin` ( which hints at the answer you're asking for as well…). – deceze Aug 03 '22 at 11:48
  • I wish, however this is part of a graphing calculator running taylor series, It needs to work for any equation a user inputs, I can't make a function for every Mathematical equation. – Gamaray Aug 03 '22 at 11:57
  • 1
    Then use a dedicated parser for this, not `eval`: https://stackoverflow.com/q/2276021/476 – deceze Aug 03 '22 at 11:59
  • Ah, that would work. Thank you. – Gamaray Aug 03 '22 at 12:03

2 Answers2

0

This is what the with keyword is for... I wouldn't recommend using it though, as it's generally discouraged, but if you want to, it's there.

Jack_Hu
  • 857
  • 6
  • 17
0

Alternatively add it to the Number prototype - it is not worse than eval

Number.prototype.sin = function() { return Math.sin(this) };
const val = Math.PI / 2
console.log(val.sin())
mplungjan
  • 169,008
  • 28
  • 173
  • 236