| 12345678910111213141516171819202122232425262728293031323334 |
-
- export default class Queue { //队列:指针移动 (最优)。 数据量大的时候比用Map速度快
- constructor() {
- this.buffer = [];
- this.head = 0;
- this.tail = 0;
- }
- getHead(){
- return this.buffer[this.head];
- }
- dequeue() {//从头部取出
- if (this.head >= this.tail) return null;
- const item = this.buffer[this.head];
- this.buffer[this.head] = undefined; // 帮助GC
- this.head++;
-
- // 定期清理前部空间
- if (this.head > 10000 && this.head > this.buffer.length / 2) {
- this.buffer = this.buffer.slice(this.head);
- this.tail -= this.head;
- this.head = 0;
- }
- return item;
- }
-
- enqueue(item) {//从尾部追加
- this.buffer[this.tail] = item;
- this.tail++;
- }
- }
|