简体   繁体   中英

What is the best way to create a queue in javascript?

I know that javascript has push / shift / pop properties that help to create this type of data structure. But I understand that using them on giant data is not such a good idea, because it must go through the entire array to execute the action. So.. What would an example of efficient code look like?

This is my code, but when using "dequeue" when deleting an element it is still stored in memory even though it has the value "null", how could I avoid this?

class Queue {
  constructor() {
    this.items = {},
      this.front = 0,
      this.end = 0;
  }

  enqueue(data) {
    this.items[this.end] = data;
    this.end++;
  }

  dequeue() {
    if (this.front === this.end) {
      return null;
    }
    const data = this.item[this.front];
    this.front++;
    return data;
  }

  getSize() {
    return this.end - this.front;
  }
}

Here's a good implementation for the Queue Data structure that will solve your problem.

class Queue {

  constructor() {
    this.first = 0;
    this.last = 0;
    this.storage = {};
  }

  enqueue(value) {
    this.storage[this.last] = value;
    this.last++;
  }

  dequeue() {
    if (this.last > this.first) {
      var value = this.storage[this.first];
      this.first++;
      return value;
    } else {
      return 0;
    }
  }

  size() {
    return this.last - this.first;
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM