I am trying to evaluate a prefix expression. I got the code from link but for some reason I run into a maximum call size exceeded and not able to debug. Can someone help me please?

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

Any help to get this work is highly appreciated. Please advice.

0 Answers