Node.js: 使用 Math 方法而不引用模块

Node.js: use Math methods without refer to module

在科学包 运行 over Node.js 中,我需要执行用户提供的数学表达式,如 "sin(2*PI*x)"。目前,它的实现类似于:

// 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);

问题是用户必须键入 Math.sin(3*x) 而不是更简单的 sin(3*x)。有什么办法可以跳过这个问题吗?

如果不可能,我将寻找一个 "replace" 调用,该调用从 1+sin(3*x).

构造字符串 1+Math.sin(3*x)

您可以查看 Math 是否有同名的 属性 并将该部分替换为其他 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);