Search code examples
javascriptpostfix-notationinfix-notation

Javascript pushing operators to a stack from a string


I am currently writing a program in Javascript where the user enters in an infix notation expression as a string which will then be converted to postfix notation. I'm having trouble pushing each operator to the stack. Below are the two main portions of code pertinent to my question.

var input = readLine();
postfixCalc(input);

//main function that converts an infix notation function to postfix
function postfixCalc (input) {
  var operatorStack = new Stack();
  print("length of input: " + input.length);//DEBUG
  for (var i = 0; i < input.length; i++) {
    if (isOperator(input[i])) {
      operatorStack.push(input[i]);
      print("Pushing to stack: " + input[i]);//DEBUG
    } else {
      print("Not an operator: " + input[i]);//DEBUG
    }
    print("This is what the input character is: " + input[i]);//DEBUG
  }
}

//This function takes the current character being looked at in postfixCalc
//and returns true or false, depending on if the current character is 
//a valid operator
function isOperator(y) {
  //if y is a valid operator, return true.
  if (y===("+" || "-" || "*" || "/" || "(" || ")")) {
    print("What is being looked at: " + y);
    return true;
  } else {
    return false;
  }
}

Only the first character compared in this line if (y===("+" || "-" || "*" || "/" || "(" || ")")) { from a given string is pushed to the stack. The string I've been using to test with has been "3*5+6". Any thoughts as to why this might be?


Solution

  • Your check

     y===("+" || "-" || "*" || "/" || "(" || ")"))
    

    is just

    y==="+"
    

    You either needs to break it up as

    if (y==="+" || y==="-" || ...) 
    

    or you can use indexOf with an array or sting.

    if (["+","-","*","/","(",")"].indexOf(y) > -1)
    

    or a regular expression