Queue.js 855 B

12345678910111213141516171819202122232425262728293031323334
  1. export default class Queue { //队列:指针移动 (最优)。 数据量大的时候比用Map速度快
  2. constructor() {
  3. this.buffer = [];
  4. this.head = 0;
  5. this.tail = 0;
  6. }
  7. getHead(){
  8. return this.buffer[this.head];
  9. }
  10. dequeue() {//从头部取出
  11. if (this.head >= this.tail) return null;
  12. const item = this.buffer[this.head];
  13. this.buffer[this.head] = undefined; // 帮助GC
  14. this.head++;
  15. // 定期清理前部空间
  16. if (this.head > 10000 && this.head > this.buffer.length / 2) {
  17. this.buffer = this.buffer.slice(this.head);
  18. this.tail -= this.head;
  19. this.head = 0;
  20. }
  21. return item;
  22. }
  23. enqueue(item) {//从尾部追加
  24. this.buffer[this.tail] = item;
  25. this.tail++;
  26. }
  27. }