Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

whats the problem in my code? I want to implement a JavaScript stack function and it resulted to NaN

//2
function Stack(){
    this.dataStore=[];
    this.top = 0;
    this.push = push;
    this.pop = pop;
    this.peek = peek;
    this.length = length;
    this.clear = clear;
}
function push(element){
    this.dataStore[this.top++] = element;
}
function pop(){
    this.dataStore[--this.top];
}
function peek(){
    return this.dataStore[this.top-1];
}
function length(){
    return this.top;
}
function clear(){
    this.top = 0;
}

var input = "100/5";
var operands = new Stack();
var operators = new Stack();

var operandsFlip = new Stack();
var postfixStr = "";

function convertInfixToPostfix(input) {
  var numStr = "";

  for (var i = 0; i < input.length; i++) {
    var curr = input[i];
    if (curr === "+" || curr === "-" || curr === "*" || curr === "/") {
      operators.push(curr);
      operands.push(numStr);
      numStr = "";
    } else {
      numStr += curr; 
    }
  }
  operands.push(numStr); 

  
  while (operands.length() > 0) {
    operandsFlip.push(operands.pop());
  }

  var operand1 = operandsFlip.pop();
  var operand2 = operandsFlip.pop();
  var operator = operators.pop();

  console.log("Postfix expression: " + operand1 + " " + operand2 + " " + operator);

  var result = eval(operand1 + operator + operand2);
  console.log("Posfix evaluated: " + result);
}

convertInfixToPostfix(input);

A postfix expression evaluator works on arithmetic expressions taking the following
form:
op1 op2 operator
Using two stacks—one for the operands and one for the operators—design and
implement a JavaScript function that converts infix expressions to postfix expres‐
sions, and then use the stacks to evaluate the expression.

and this is the output:

Postfix expression: undefined undefined undefined Posfix evaluated: NaN

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your pop() function misses the return keyword and therefore always returns undefined.

function pop(){
    return this.dataStore[--this.top];
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading