Skip to content

Instantly share code, notes, and snippets.

@maecapozzi
Last active November 3, 2017 18:24
Show Gist options
  • Save maecapozzi/f13116dcf0de4deb2e4df25c72452b61 to your computer and use it in GitHub Desktop.
Save maecapozzi/f13116dcf0de4deb2e4df25c72452b61 to your computer and use it in GitHub Desktop.
Stack Implementation in JavaScript
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