JavaScript "functional" approach


  • 1
    A
    // map operator strings to functions
    const map = {
      '+': add,
      '-': subtract,
      '*': multiply,
      '/': divide
    };
    
    /**
     * @param {string[]} tokens
     * @return {number}
     */
    function evalRPN(tokens) {
      let stack = [];
    
      for (let n of tokens) {
        // if operator function exists, 
        // execute it on the two most recent numbers
        if (map[n]) {
          let fn = map[n];
          let y = stack.pop();
          let x = stack.pop();
    
          stack.push(fn(x, y));
        } else {
          stack.push(Number(n));
        }
      }
    
      return head(stack);
    }
    
    // helper methods
    function add(x, y) {
      return x + y;
    }
    
    function subtract(x, y) {
      return x - y;
    }
    
    function multiply(x, y) {
      return x * y;
    }
    
    function divide(x, y) {
      return parseInt(x / y);
    }
    
    function head(list) {
      return list[0];
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.