Stack Demo in JS
Data Structure Implementation
by dpnminh
HTML
<div>
<h4>
Stack Operation Demo
</h4>
<div class="line">
<div class="Insert" >
<input id="insert" name='insert' placeholder='Add an element to stack'>
<button onclick="stackPerform('push')">
Push
</button>
</div>
<div class="line">
<button onclick="stackPerform('pop')">
Pop
</button>
<button onclick="stackPerform('stackEmpty')">
Empty Stack
</button>
</div>
</div>
<div class="seperate-line">
</div>
<div class="result line">
<div id="current-status" class="line">
</div>
<div id="current-size" class="line"></div>
<div id="last-added" class="line">
</div>
<div id="stack-look" class="line">
</div>
</div>
</div>
CSS
html, *{
font-family: Arial;
font-size: 0.9rem;
}
button{
padding: 0.5rem;
background: #2fb1cc;
color:white;
border: none;
}
button:hover{
cursor:pointer;
}
#insert{
padding: 0.4rem;
min-width: 50%;
}
.line{
margin-top: 0.5rem;
}
.seperate-line{
height: 2px;
background: #dad5d5;
margin: 1rem 0;
width: 100%;
}
#current-status{
color: green;
}
JavaScript
function Stack(){
var stack = {};
var stackSize = 0;
return {
push: function(item){
stack[stackSize] = item;
stackSize++;
},
pop: function(){
if (this.isEmpty()){
return undefined;
}
stackSize--;
var item = stack[stackSize];
delete stack[stackSize];
return item;
},
peek: function(){
if (this.isEmpty()){
return undefined;
}
return stack[stackSize - 1];
},
stackEmpty: function(){
while (!this.isEmpty()){
this.pop();
}
},
isEmpty: function(){
return stackSize === 0;
},
size: function(){
return stackSize;
},
print: function(){
var result = [];
for (var key in stack){
result.unshift(stack[key]);
}
return result;
}
}
}
var demoStack = new Stack();
function stackPerform(type){
var status = document.getElementById('current-status');
status.innerHTML = 'Status: Processing...';
if (type === 'push'){
var item = document.getElementById('insert').value;
if (item){
demoStack.push(item);
}
}
else{
demoStack[type]();
}
printStackDetails();
printStackToScreen();
status.innerHTML = 'Status: Completed.'
}
function printStackDetails(){
var size = demoStack.size();
var lastAdded = demoStack.peek() || 'N/A';
document.getElementById('current-size').innerHTML = 'Size of stack: ' + size;
document.getElementById('last-added').innerHTML = 'Last added to Stack: ' + lastAdded;
}
function printStackToScreen(){
var stackInPrint = demoStack.print();
var display = document.getElementById('stack-look');
display.innerHTML = '';
var DisplayLabel = document.createElement('div');
DisplayLabel.setAttribute('class', 'stack-label');
DisplayLabel.innerHTML = 'Demo Stack: '
display.appendChild(DisplayLabel);
for (var i = 0; i < stackInPrint.length;...