Skip to content

Instantly share code, notes, and snippets.

@bramantyoa
Created October 28, 2016 00:35
Show Gist options
  • Save bramantyoa/9706715cc507f1478a41b1a41fe5cd58 to your computer and use it in GitHub Desktop.
Save bramantyoa/9706715cc507f1478a41b1a41fe5cd58 to your computer and use it in GitHub Desktop.
My attemp to recall a simple stack implementation in JavaScipt
/**
From: A Gentle Introduction to Data Structures: How Stacks Work
By: Michael Olorunnisola
https://medium.freecodecamp.com/data-structures-stacks-on-stacks-c25f2633c529
**/
class Stack {
/**
the underscore before the variable names signifies to other developers these variables are private,
and shouldn’t be manipulated externally, only by the methods on the class
**/
constructor() {
this._storage = {};
this._position = -1;
}
/**
to return the current position of the stack
**/
top() {
return this._position();
}
/**
add item to the stack
**/
push(value) {
this._position++;
this._storage[this._position] = value;
}
/**
remove item from the stack
**/
pop(){
// Check if the stack is not empty
if(this._position > -1){
let val = this._storage[this._position];
delete this._storage[this._position];
this._position--;
return val;
}
}
}
// Make a browser history stack
let browserHistory = new Stack();
// Make a stack to save deleted history so we can access it again later (Forward Button)
let forward = new Stack();
// Insert value to stack (We accessed these sites in order)
browserHistory.push("www.google.com"); // Navigating to google
browserHistory.push("www.facebook.com"); // Navigating to facebook
browserHistory.push("www.github.com"); // Current site
// Delete one entry -- Add it to forward stack to make it accessible
forward.push(browserHistory.pop()); // Returns www.github.com
// www.facebook.com is now our current site, we need to get back to github so ...
browserHistory.push(forward.pop());
// www.github.com is now our current site
// Clear forward stack when I navigate to a new site
while(forward.top() > -1){
forward.pop();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment