EXERCISE · AlgoCasts
Stack
Create a stack data structure. The stack should be a class with methods 'push', 'pop', and 'peek'. Adding an element to the stack should store it until it is removed.
Directions
Directions
Create a stack data structure. The stack should be a class with methods 'push', 'pop', and 'peek'. Adding an element to the stack should store it until it is removed.
Examples#
JS
const s = new Stack();s.push(1);s.push(2);s.pop(); // returns 2s.pop(); // returns 1Try it first#
Copy the stub, make the 4 tests pass on your machine, then open the solution. The reveal is remembered per page in this browser.
JSexercises/stack/index.js
class Stack {} module.exports = Stack;Solution#
JScompleted_exercises/stack/index.js
class Stack { constructor() { this.data = []; } push(record) { this.data.push(record); } pop() { return this.data.pop(); } peek() { return this.data[this.data.length - 1]; }} module.exports = Stack;const Stack = require('./index'); test('Stack is a class', () => { expect(typeof Stack.prototype.constructor).toEqual('function');}); test('stack can add and remove items', () => { const s = new Stack(); s.push(1); expect(s.pop()).toEqual(1); s.push(2); expect(s.pop()).toEqual(2);}); test('stack can follows first in, last out', () => { const s = new Stack(); s.push(1); s.push(2); s.push(3); expect(s.pop()).toEqual(3); expect(s.pop()).toEqual(2); expect(s.pop()).toEqual(1);}); test('peek returns the first element but doesnt pop it', () => { const s = new Stack(); s.push(1); s.push(2); s.push(3); expect(s.peek()).toEqual(3); expect(s.pop()).toEqual(3); expect(s.peek()).toEqual(2); expect(s.pop()).toEqual(2); expect(s.peek()).toEqual(1); expect(s.pop()).toEqual(1);}); Verbatim from the repo at 30cf7634. Alternate tabs are the commented-out solutions with the leading // removed and nothing else changed. Run the tests locally with npx jest stack inside the fork.
See also