Last active
December 31, 2018 16:39
-
-
Save nfroidure/5472493 to your computer and use it in GitHub Desktop.
A simple Javascript Stack based on an Array wrap. More explanations here : https://insertafter.com/blog-fifo_lifo_javascript.html
This file contains 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
class Stack { | |
constructor(...elements) { | |
// Initializing the stack with given arguments | |
this.elements = [...elements]; | |
} | |
// Proxying the push/shift methods | |
push(...args) { | |
return this.elements.push(...args); | |
} | |
pop(...args) { | |
return this.elements.pop(...args); | |
} | |
// Add some length utility methods | |
getLength(...args) { | |
return this.elements.length; | |
} | |
setLength(length) { | |
return this.elements.length = length; | |
} | |
} | |
const s = new Stack(0,1); | |
s.push(2); | |
console.log(s.getLength()); // 3 | |
while(s.getLength()) | |
console.log(s.pop()); // 2, 1, 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment