Skip to content

Instantly share code, notes, and snippets.

@pllearns
Created May 20, 2017 23:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pllearns/26fdc1b5bfef5f226fbd84069d9c1365 to your computer and use it in GitHub Desktop.
Save pllearns/26fdc1b5bfef5f226fbd84069d9c1365 to your computer and use it in GitHub Desktop.
Stack in ES6
'use strict'
class Stack {
constructor(capacity) {
this._capacity = capacity || Infinity
this._storage = {}
this._count = 0
}
push(value) {
if (this._count < this._capacity) {
this._storage[this._count++] = value
return this._count
}
return 'Max capacity reached. Remove an element before adding a new one'
}
pop() {
let value = this._storage[--this._count]
delete this._storage[this._count]
if (this._count < 0) {
this._count = 0
}
return value
}
peek() {
return this._storage[this._count-1]
}
count() {
return this._count
}
}
var myStack = new Stack(3)
console.log(myStack.push('a'))
console.log(myStack.push('b'))
console.log(myStack.push('c'))
console.log(myStack.push('d'))
console.log(myStack.pop())
console.log(myStack.count())
console.log(myStack.peek())
console.log(myStack.count())
class MinStack {
constructor(capacity) {
this._capacity = capacity
this._storage = {}
this._count = 0
this._min = new Stack()
}
push() {
if(this._count < this._capacity) {
if(this._min.peek() < value) {
this._min.push(this._min.peek())
} else {
this._min.push(value)
}
this._storage[this._count++] = value
return this._count
}
return 'Max capacity reached Remove element before adding a new one'
}
pop() {
this._min.pop()
let value = this._storage[--this._count]
delete this._storage[this._count]
if (this._count < 0) {
this._count = 0
}
return value
}
peek() {
return this._storage[this._count-1]
}
count() {
return this._count
}
min() {
return this._min.peek()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment