dastack
All of the implementations of stacks I found attached everything to the
prototype
and didn't make good use of private encapsulation, getters,
non-enumerable methods, etc.
So here it is, a clean implementation of a stack written in straight simple es5.
API
Create a stack
var createStack = ; var stack = ; // => Creates an empty stack var stack = ; // => Creates a stack with initial values
stack.size
The only property on the stack is size
, works exactly the same as the length
property on Array.
var stack = ; stacksize // => 3
stack.push()
Add a new element to the top of the stack.
var stack2 = ; stacksize // => 3
stack.pop()
Remove the top element from the top of the stack.
var stack = ; stack // => 3 stacksize // => 2
stack.peek()
Get the top element from the top of the stack, but do not remove it.
var stack = ; stack // => 3 stacksize // => 3
stack.clear()
Empty the stack.
var stack = ; stackclear stacksize // => 0
stack.toString()
Get the current stack as a string.
var stack = ; stack // => "1,2,3"
stack.toArray()
Copy the current stack into a regular array.
var stack = ; stack // => [1, 2, 3]