JSImplement queue structure

One, foreword

Queue is a special kind of linear table. What is special is that it only allows deletion in the front of the table and insertion in the rear of the table. It is a first-in, first-out (FIFO) data structure. The end that performs the insert operation is called the tail of the queue, and the end that performs the delete operation is called the head of the queue.

If you want to use JS to implement queue structure, you need to ensure that the implementation of the queue has the following basic functions:

  • New element to enqueue

  • Dequeue removes the element at the head of the queue and returns its value

  • Front returns the element at the head of the queue

  • Clear Clear the queue

  • Size Specifies the size of the queue, that is, the number of elements

  • IsEmpty indicates whether the queue isEmpty

    Once you know what you want to implement, you can start implementing the queue

Second, the implementation of queue

const Queue = (function () { const _items = new WeakMap() return class { constructor() { _items.set(this, [])} enqueue(el) {_items.get(this).push(el)} dequeue() {return _items.get(this).shift()} Front () {return _items.get(this)[0]} // Clear the queue () {_items.set(this, [])} // queue size() {return _items.get(this).length} // whether the queue isEmpty isEmpty() {return _items.get(this).length === 0}} })() const queue = new Queue() queue.enqueue(1) queue.enqueue(2) queue.enqueue(3) console.log(queue.size()) // 3 console.log(queue.isEmpty()) // false queue.clear() console.log(queue.size()) // 0 console.log(queue.isEmpty()) // trueCopy the code