Queue Data Structure in JavaScript
Level 5493 keystrokes
Implements a FIFO (first in, first out) queue on top of an array. After enqueuing "first", "second" and "third" it prints the front ("first"), two dequeues ("first", then "second"), the size (1) and the new front ("third").
JavaScript code
// A queue class: items join at the end and leave from the front1class Queue { // Starts with an empty array of items2 constructor() { this.items = []; } // Adds an item at the back of the queue3 enqueue(item) { this.items.push(item); } // shift removes and returns the front item, the oldest one4 dequeue() { return this.items.shift(); } // Returns the front item without removing it5 front() { return this.items[0]; } // true when the queue has no items6 isEmpty() { return this.items.length === 0; } // Returns the number of items7 size() { return this.items.length; }8}9 // Creates an empty queue10const queue = new Queue();// Adds three items; "first" is at the front, "third" at the back11queue.enqueue("first");12queue.enqueue("second");13queue.enqueue("third");// Prints first; the item stays in the queue14console.log(queue.front());// Removes and prints first, the item added first15console.log(queue.dequeue());// Removes and prints second16console.log(queue.dequeue());// Prints 1, because only "third" is left17console.log(queue.size());// The front is now third18console.log(queue.front());Output
first first second 1 third
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this JavaScript code and how often they appear.
.× 23(× 22)× 22;× 15{× 7}× 7"× 6=× 5[× 2]× 2