Search code examples
javascriptnode.jsimportrequire

Node.js: use Math methods without refer to module


In a scientific package running over Node.js I need to execute user provided mathematical expressions like "sin(2*PI*x)". Currently, it is implemented similar to:

// from input: s = "1+Math.sin(2*Math.PI*x)";
...
// regexp to verify "s" doesn't contains dangerous characters as '";
...
val f = new Function( 'x', s );
...
f(12);

The problem is user must type Math.sin(3*x) instead of a more simple sin(3*x). Is there any way to skip this problem ?

If not possible, I will look for a "replace" call that constructs the string 1+Math.sin(3*x) from 1+sin(3*x).


Solution

  • You could look if Math has a property with the same name and replace the part with additional Math..

    var string = "sin(3*x)+foo()+PI*Math.PI",
        result = string.replace(/[a-z][\d.a-z]*(?=\(|[^\da-z]|$)/ig, k => (k in Math ? 'Math.' : '') + k);
    
    console.log(result);