Last active
November 3, 2017 18:24
-
-
Save maecapozzi/f13116dcf0de4deb2e4df25c72452b61 to your computer and use it in GitHub Desktop.
Stack Implementation in JavaScript
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 () { | |
this.state = { | |
storage: '', | |
count: 0, | |
mostRecent: '' | |
} | |
}; | |
push (value) { | |
this.state.storage = this.state.storage + '***' + value; | |
this.state.count = this.updateCount(1); | |
this.state.mostRecent = value; | |
}; | |
findDelimiter (value) { | |
return this.state.storage.lastIndexOf(value); | |
}; | |
sliceString (delimiter, index) { | |
return this.state.storage.slice(delimiter + 3, index); | |
}; | |
updateCount (amount) { | |
return this.state.count + amount; | |
}; | |
pop () { | |
const str = this.sliceString(this.findDelimiter('***')); | |
this.state.storage = this.state.storage.substring(0, this.findDelimiter('***')); | |
this.state.count = this.updateCount(-1); | |
this.state.mostRecent = this.sliceString(this.findDelimiter('***'), this.state.storage.length) | |
return str; | |
}; | |
count () { | |
return this.state.count; | |
}; | |
peek () { | |
return this.state.mostRecent; | |
}; | |
} | |
const myStack = new Stack(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment