2

我试图通过评估表达式中的一个特定函数调用来模仿 JavaScript 中的惰性求值,同时保持其他函数不变。是否可以只计算表达式中的一个函数而不计算其他函数(以便表达式中的所有其他函数调用保持原样)?

这是我要实现的功能:

function evaluateSpecificFunction(theExpression, functionsToEvaluate){
    //Evaluate one specific function in the expression, and return the new expression, with one specific function being evaluated
}

例如:

evaluateSpecificFunction("addTwoNumbers(1, 2) + getGreatestPrimeFactor(10)", addTwoNumbers);
//This should return "3 + getGreatestPrimeFactor(10)", since only one of the functions is being evaluated

evaluateSpecificFunction("addTwoNumbers(1, 2) + getGreatestPrimeFactor(10)", getGreatestPrimeFactor);
//This should return "addTwoNumbers(1, 2) + 5";
4

1 回答 1

3

您可以做的是使用替换和正则表达式:

function getGreatestPrimeFactor(n) {
  return n*2;
}

function transform(s, f) {
  return s.replace(new RegExp(f+"\\(([^\\)]*)\\)", "g"), function(m, args) {
    return window[f].apply(null, args.split(',').map(function(v){
       return parseFloat(v)
    }));
  });
}


var result = transform(
    "addTwoNumbers(1, 2) + getGreatestPrimeFactor(10)",
    "getGreatestPrimeFactor"
);

此示例假设您只处理数字参数。

演示(打开控制台)

当然,这段代码主要展示了这个想法,例如,您应该将函数存储在专用对象中,而不是全局上下文(window)中。

编辑:新版本可以处理多个替换。

于 2013-05-01T18:14:13.010 回答