评估前缀表达式的值-JS

时间:2019-05-18 15:26:55

标签: javascript

我正在尝试评估前缀表达式。我从link获得了代码,但是由于某种原因,我遇到了超出最大调用大小且无法调试的问题。有人可以帮我吗?

var operators = {
  '+': function(a, b) {
    return a + b;
  },
  '-': function(a, b) {
    return a - b;
  },
  '*': function(a, b) {
    return a * b;
  },
  '/': function(a, b) {
    return a / b;
  },
};
var precedence = [
  ['*', '/'],
  ['+', '-']
]

function evalPrefix(input, variable) {
  // process at this level
  // return the result of this level and what we didn't use
  // return a null value if we fail at any point
  function step(current) {
    // directly return numbers
    if (!isNaN(parseFloat(current[0]))) {
      return {
        value: parseFloat(current[0]),
        rest: current.slice(1)
      };
    }

    // otherwise, we're going to have to recur
    else {
      var f = operators[current[0]];

      // recur for left, use that rest for right
      var left = step(current.slice(1));
      if (left.value == null) return {
        value: null,
        rest: []
      };
      var right = step(left.rest);
      if (right.value == null) return {
        value: null,
        rest: []
      };

      // return at my level
      return {
        value: f(left.value, right.value),
        rest: right.rest
      };
    }
  }
  return step(input).value;
}

console.log(evalPrefix('+ x y', {x: 1, y: 5})); //6
console.log(evalPrefix('+ 1 5')); //6

任何帮助获得这项工作的帮助都受到高度赞赏。请指教。

0 个答案:

没有答案