Skip to content

Instantly share code, notes, and snippets.

@RoryDuncan
Created February 6, 2014 20:40
Show Gist options
  • Save RoryDuncan/8852089 to your computer and use it in GitHub Desktop.
Save RoryDuncan/8852089 to your computer and use it in GitHub Desktop.
A stack object which can be used similar to a queue or whatnot.
var Stack = (function() {
var list = []; // Private to the instance.
var append = function() {
for ( var x = 0, xx = arguments.length; x< xx; x++ ) {
list.push( arguments[x] );
}
return this;
};
var prepend = function(value){
list.unshift(value);
return this;
};
var add = function() {
// edge case where list is empty
if ( !list.length ) {
// [object Arguments] doesn't natively have a .forEach method :'[
for (var x = 0, xx = arguments.length - 1; x < xx; x++) {
append( arguments[x] );
}
};
var index = arguments[arguments.length - 1];
var p1 = list.slice(0, index);
var p2 = list.slice(index);
for (x = 0, xx = arguments.length - 1; x < xx; x++) {
p1.push( arguments[x] );
}
list = p1.concat(p2);
return this;
};
var pop = function(){
var recent = list.length - 1;
this.popped = function(){ return list[recent]};
this.remove( recent );
return this;
};
var get = function(index){
if (index) return list[index];
else return list;
};
var remove = function(index){
delete list[index];
return this;
};
this.prepend = this.unshift = prepend;
this.add = this.put = add;
this.pop = this.last = pop;
this.push = this.append = append;
this.remove = this.delete = remove;
this.get = get;
// whitespace is for nerds
this.clear = function(){list = [];return this;};
this.log = function(){console.log(list);return this;};
this.toString = function(){return "[object Stack]";}; // fancy
return this;
});
// global time
window.Stack = Stack;
var z = new Stack();
// sweet chains, bae.
z.push(1, 2, 6, 7, 8, 9, 10)
.clear()
.add(3,4,5, 2)
.push("wow hi!", "Let's Dance, scoundrel!!!", "wat wat")
.pop()
.log()
.get();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment