1

Using typescript, I need to convert some strings like "Math.floor" and "console.log" to the functions Math.floor and console.log, in order to be able to use those functions when passed as a string parameter.

For example

applyFunction ("Math.floor", 4.2); // => Math.floor(4.2) => 4
applyFunction ("console.log", "Hi"); // => console.log("Hi") => Hi

And so on.

I tried adding them as keys and values in an object and scanning the object whenever needed. But since I don't have the time to continuously search for and add all existing Typescript functions, I'm looking for a more comprehensive approach.

TamerB
  • 1,401
  • 1
  • 12
  • 27

2 Answers2

3

FWIW you can use eval() to parse strings as code.

Example:

eval("console.log('foo')")

That being said, I'd advice you to be careful when using eval().

nicholaswmin
  • 21,686
  • 15
  • 91
  • 167
1

If you are using the browser you can do:

window['Math']['floor'](4.2);
window['console']['log']('Hi');

Make sure you iterate over the namespaces, eval(string) works better.

Fals
  • 6,813
  • 4
  • 23
  • 43