EXERCISE · AlgoCasts
Queue
Create a queue data structure. The queue should be a class with methods 'add' and 'remove'.
Directions
Directions
Create a queue data structure. The queue should be a class with methods 'add' and 'remove'. Adding to the queue should store an element until it is removed
Examples#
JS
const q = new Queue(); q.add(1); q.remove(); // returns 1;Try 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/queue/index.js
class Queue {} module.exports = Queue;Solution#
JScompleted_exercises/queue/index.js
class Queue { constructor() { this.data = []; } add(record) { this.data.unshift(record); } remove() { return this.data.pop(); }} module.exports = Queue;const Queue = require('./index'); test('Queue is a class', () => { expect(typeof Queue.prototype.constructor).toEqual('function');}); test('can add elements to a queue', () => { const q = new Queue(); expect(() => { q.add(1); }).not.toThrow();}); test('can remove elements from a queue', () => { const q = new Queue(); expect(() => { q.add(1); q.remove(); }).not.toThrow();}); test('Order of elements is maintained', () => { const q = new Queue(); q.add(1); q.add(2); q.add(3); expect(q.remove()).toEqual(1); expect(q.remove()).toEqual(2); expect(q.remove()).toEqual(3); expect(q.remove()).toEqual(undefined);}); 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 queue inside the fork.
See also