Lingquan | Blog

Implement a Queue by Javascript

Word count: 122Reading time: 1 min
2018/10/22 Share

How to Implement a Queue by Javascript

We got two methods:

  1. use array and shift method for dequeue
  2. use object and two pointers, see code below
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    class Queue {
    constructor() {
    this._storage = {};
    this._oldIndex = 0;
    this._newIndex = 0;
    }

    enqueue(ele) {
    this._storage[this._newIndex] = ele;
    this._newIndex += 1;
    }

    dequeue() {
    if (this._oldIndex !== this._newIndex) {
    let dequeueData = this._storage[this._oldIndex];
    delete this._storage[this._oldIndex];
    this._oldIndex += 1;

    return dequeueData;
    }

    }

    size() {
    return this._newIndex - this._oldIndex;
    }

    isEmpty() {
    return this.size() === 0;
    }
    }

Test

1
2
3
4
5
6
7
8
let queue = new Queue();
queue.enqueue(10);
queue.enqueue(11);
queue.enqueue(12);
console.log(queue.dequeue())
console.log(queue)
console.log(queue.isEmpty())
console.log(queue.size())
CATALOG
  1. 1. How to Implement a Queue by Javascript
  2. 2. Test