Skip to content

Instantly share code, notes, and snippets.

@softwarespot
Last active October 31, 2015 08:24
Show Gist options
  • Save softwarespot/2561af61e8b9ba87c2ec to your computer and use it in GitHub Desktop.
Save softwarespot/2561af61e8b9ba87c2ec to your computer and use it in GitHub Desktop.
A stack in JavaScript with ES2015
// Note: Save as stack.js and run 'babel-node stack.js' to display in the command window. This is written in ES2015
((global) => {
// Note: I'm aware .pop() and .push() exist natively with JavaScript arrays, but where's the fun in that? =)
/**
* Stack interface
*/
function Stack() {
this._stack = [];
this._index = -1;
}
/**
* Append functions to the Stack prototype chain
* @type {object}
*/
Stack.prototype = {
/**
* Peek at the last item placed last on the stack
*
* @return {mixed|null} Last item placed on the stack; otherwise, null
*/
peek: () => {
const index = this._index;
if (index === -1) {
return null;
}
return this._stack[index];
},
/**
* Pop the last item off the stack
*
* @return {mixed|null} Last item placed on the stack; otherwise, null
*/
pop: () => {
if (this._index === -1) {
return null;
}
// Return the data at the current index and decrement the index too
return this._stack[this._index--];
},
/**
* Puah data on to the stack
*
* @param {mixed} data Data to push on to the stack
* @return {undefined}
*/
push: (data) => {
// Increment the index and push the data on to the stack at the index value
this._stack[++this._index] = data;
},
// Helper functions
/**
* Get the number of items on the stack
*
* @return {number} Number of items on the stack
*/
count: () => {
return this._index + 1;
},
};
// Example
(() => {
// Create a stack
const stack = new Stack();
global.console.log('Stack peek: ', stack.peek());
global.console.log('Stack pop: ', stack.pop());
global.console.log('Stack count: ', stack.count());
// Push primitive datatypes e.g. string, number
stack.push('Some data 1');
stack.push('Some data 2');
stack.push('Some data 3');
global.console.log('Stack peek: ', stack.peek());
global.console.log('Stack count: ', stack.count());
global.console.log('Stack pop: ', stack.pop());
global.console.log('Stack pop: ', stack.pop());
global.console.log('Stack pop: ', stack.pop());
// There should be no items left on the stack
global.console.log('Stack pop: ', stack.pop());
global.console.log('Stack count: ', stack.count());
// Push on to the stack again
stack.push('Some data 1');
global.console.log('Stack peek: ', stack.peek());
global.console.log('Stack count: ', stack.count());
})();
})(window); // An IIFE for function scope i.e. creating a namespace
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment