Implement a Stack computer in Javascript (you will turn in a link to your progra
ID: 3675809 • Letter: I
Question
Implement a Stack computer in Javascript (you will turn in a link to your program in JSFiddle). This is a simple computer that keeps a stack, when a number is entered it goes onto the top of the stack. When an operation is entered, the previous 2 numbers are operated on by the operation.
For example
2 [enter] 2
5 [enter] 5 2
* [enter] * 5 2 -> collapses to 10
would leave at 10 at the top of the stack.
The program should use a simple input box, either a text field or prompt and display the contents of the Stack.
Explanation / Answer
https://jsfiddle.net/7hz33ddq/
please find
<input type="text" id="textBox">
<input type="submit" value="submit">
<button>Submit2</button>
<div id="myDiv">
</div>
<script>
var addEntry=function addEntry(){
var inputs=document.getElementById("textBox").value;
if(inputs=='%'){
var a=stack.pop();
var b=stack.pop();
var c=a%b;
stack.push(c);
stack.print();
}
else if(inputs=='*'){
var a=stack.pop();
var b=stack.pop();
var c=a*b;
stack.push(c);
stack.print();
} else if(inputs=='+'){
var a=stack.pop();
var b=stack.pop();
var c=a+b;
stack.push(c);
stack.print();
} else if(inputs=='-'){
var a=stack.pop();
var b=stack.pop();
var c=a-b;
stack.push(c);
stack.print();
}else{
var c=document.getElementById("textBox").value;
c=parseInt(c);
stack.push(c);
stack.print();
}
}
function Stack() {
var items = [];
this.push = function(element){
items.push(element);
};
this.pop = function(){
return items.pop();
};
this.peek = function(){
return items[items.length-1];
};
this.isEmpty = function(){
return items.length == 0;
};
this.size = function(){
return items.length;
};
this.clear = function(){
items = [];
};
this.print = function(){
console.log(items.toString());
document.getElementById("myDiv").innerHTML=items.toString()
};
}
(function(){
stack = new Stack();
})();
</script>
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.