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.

2 Answers 2

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().

Sign up to request clarification or add additional context in comments.

1 Comment

For me it worked as: eval("console.log")('foo'); Thanx alot
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.

5 Comments

I've posted an answer below that uses eval but I like this one better
@NicholasKyriakides eval(string) does the work better, this one is just another approach it you are in the browser, but is difficult because you must iterate over namespaces
why is it difficult, simple split and reduce
eval('Math.floor')(4.2) was much easier for my situation. Thanks a lot
concerning espacarellos comment "Math.floor".split(".").reduce((o,i)=>o[i],window)(5)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.