Created
February 23, 2020 12:18
-
-
Save claeusdev/636e1b87d10f25c60d00c5e298d63e75 to your computer and use it in GitHub Desktop.
Simple implementation of a Stack data structure in js
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
var Stack = function(capacity){ | |
this.capacity = capacity || Infinity | |
this.storage = {} | |
this.size = 0 | |
} | |
Stack.prototype.push = function(val){ | |
if(this.size < this.capacity){ | |
this.storage[this.size] = value | |
return this.size | |
} | |
return "Max capacity exceeded. Remove an element before adding a new one" | |
} | |
Stack.prototype.pop = function(){ | |
let value = this.storage[--this.size] | |
delete this.storage[this.size] | |
if(this.size < 0){ | |
this.size = 0 | |
} | |
return value | |
} | |
Stack.prototype.size = function(){ | |
return this.size | |
} | |
Stack.prototype.peek = function(){ | |
return this.storage[this.size - 1] | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment