This JavaScript Reference section displays the code for an example program that shows how to create a stack-based calculator in JavaScript.
<!DOCTYPE html> <html> <head> <title>XoaX.net's Javascript</title> <script type="text/javascript" src="StackBasedCalculator.js"></script> </head> <body onload="fnInitialization()"> <p id="idAnswer"></p> </body> </html>
// The Link Constructor function CLink(qData) { this.mqData = qData; this.mqpNext = null; } // The LinkedList Constructor function CLinkedList() { this.mqpHead = null; this.mfnInsertAtHead = function(qData) { var qpOldHead = this.mqpHead; this.mqpHead = new CLink(qData); this.mqpHead.mqpNext = qpOldHead; } this.mfnRemoveAtHead = function() { this.mqpHead = this.mqpHead.mqpNext; } this.mfnIsEmpty = function() { return (this.mqpHead == null); } } // The Stack Constructor function CStack() { this.mqList = new CLinkedList(); this.mfnPush = function(qData) { this.mqList.mfnInsertAtHead(qData); } this.mfnPop = function() { var qPopped = this.mqList.mqpHead; this.mqList.mfnRemoveAtHead(); return qPopped.mqData; } this.mfnIsEmpty = function() { return this.mqList.mfnIsEmpty(); } } function fnInitialization() { // The expression must have parentheses around each operation // Each number must be a single digit and positive. var sExpression = "((((3*4)+(5*2))/5)+(3*2))"; var qNumberStack = new CStack(); var qOperatorStack = new CStack(); var qpPrint = document.getElementById("idAnswer"); for (var sCurrChar of sExpression) { if (sCurrChar == '(') { // Check for a left parenthesis // We do not need to do anything in this case } else if (sCurrChar == ')') { // Check for a right parenthesis // Get the numbers in reverse order var dY = Number(qNumberStack.mfnPop()); var dX = Number(qNumberStack.mfnPop()); // Get the operation, decipher, and calculate the value. sCurrChar = qOperatorStack.mfnPop(); var dZ = 0.0 switch (sCurrChar) { case '+': { dZ = (dX + dY); break; } case '-': { dZ = (dX - dY); break; } case '*': { dZ = (dX * dY); break; } case '/': { dZ = (dX / dY); break; } } qNumberStack.mfnPush(dZ); } else if ((sCurrChar == '+') || (sCurrChar == '-') || (sCurrChar == '*') || (sCurrChar == '/')) { // Check for an operation // Push the operator value as a character onto the operator stack qOperatorStack.mfnPush(sCurrChar); } else if (sCurrChar >= '0' && sCurrChar <= '9') { // Check for a numeric digit // Push the character value as a number onto the number stack qNumberStack.mfnPush(sCurrChar); } } qpPrint.innerHTML = sExpression + " = " + Number(qNumberStack.mfnPop()) + "<br />"; }
© 20072024 XoaX.net LLC. All rights reserved.