Skip to content
This repository has been archived by the owner on Oct 7, 2019. It is now read-only.

Implemented a stack algorithm in vanilla js #100

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions data_structures/stacks/stack.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Author: Austin Crane
// this is a node program, you can run this with node stack.js

// Stack simple stack implementation
// accessed via a "private" items array
function Stack() {
this._items = [];
return this;
}

// push adds an item onto the stack
Stack.prototype.push = function(n) {
this._items.push(n);
}

// pop removes the item on the top of the stack
Stack.prototype.pop = function() {
if (this.size() === 0) {
// if your trying to access an empty stack that
// would be considered an error
console.error('reached end of stack');
return;
}
return this._items.pop();
}

// size gives the size of the stack
Stack.prototype.size = function() {
return this._items.length;
}

// simple "main" program to work with a stack
function stackExample() {
var s = new Stack()
s.push(1);
s.push(2);
s.push(3);

// print size of stack
console.log(s.size());

// 3
console.log(s.pop());
// 2
console.log(s.pop());
// 1
console.log(s.pop());

// this will log an error reach end of stack
console.log(s.pop());
}

stackExample();