Created
April 13, 2018 21:29
-
-
Save trafficinc/0d882fad8d4ab91cb32fc340284e49d1 to your computer and use it in GitHub Desktop.
JavaScript Stack Class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Stack() { | |
this.dataStore = []; | |
this.top = 0; | |
this.push = push; | |
this.pop = pop; | |
this.peek = peek; | |
this.clear = clear; | |
this.length = length; | |
} | |
function push(element) { | |
this.dataStore[this.top++] = element; | |
} | |
function peek() { | |
return this.dataStore[this.top - 1]; | |
} | |
function pop() { | |
return this.dataStore[--this.top]; | |
} | |
function clear() { | |
this.top = 0; | |
} | |
function length() { | |
return this.top; | |
} | |
var s = new Stack(); | |
s.push("Derrick"); | |
s.push("ReeRee"); | |
s.push("Laynee"); | |
console.log("length: " + s.length()); | |
console.log(s.peek()); | |
var popped = s.pop(); | |
console.log("The popped element is: " + popped); | |
console.log(s.peek()); | |
s.push("Cynthia"); | |
console.log(s.peek()); | |
s.clear(); | |
console.log("length: " + s.length()); | |
console.log(s.peek()); | |
s.push("Clayton"); | |
console.log(s.peek()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment