Skip to content

Instantly share code, notes, and snippets.

@odykyi
Created June 23, 2019 11:38
Show Gist options
  • Save odykyi/fa44965e26aac2fa73d5fe45e01fef4d to your computer and use it in GitHub Desktop.
Save odykyi/fa44965e26aac2fa73d5fe45e01fef4d to your computer and use it in GitHub Desktop.
node js javascript stack implementation example data structure
console.time('stack');
const assert = require('assert'); // for tests
class Stack {
constructor() {
this.list = []
}
isEmpty() {
return !this.list.length;
}
clear() {
this.list = [];
return this.list;
}
peek() {
if (this.isEmpty()) {
return null;
}
return this.list[0];
}
push(value) {
return this.list.unshift(value);
}
pop() {
return this.list.pop();
}
toArray() {
return [...this.list];
}
toString() {
return this.list.toString();
}
}
const stack = new Stack();
console.log('%O', stack);
assert.equal(stack.peek(), null);
assert.equal(stack.push(1), 1);
assert.equal(stack.push(2), 2);
assert.deepEqual(stack.toArray(), [2,1]);
assert.equal(stack.toString(), '2,1');
assert.equal(stack.peek(), 2);
assert.equal(stack.peek(), 2);
assert.equal(stack.isEmpty(), false);
assert.equal(stack.pop(), 1);
assert.equal(stack.pop(), 2);
assert.equal(stack.pop(), null);
assert.equal(stack.isEmpty(), true);
assert.deepEqual(stack.clear(), []);
assert.deepEqual(stack.toArray(), []);
console.timeEnd('stack');
// node stack.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment