本文参加了由公众号@若川视野 发起的每周源码共读活动, 点击了解详情一起参与。本文为个人笔记,只做关键记录。
链表结构
class Node {
value;
next;
constructor(value) {
this.value = value;
}
}
构造函数
#head;
#tail;
#size;
constructor() {
this.clear();
}
入队操作
enqueue(value) {
const node = new Node(value);
if (this.#head) {
this.#tail.next = node;
this.#tail = node;
} else {
this.#head = node;
this.#tail = node;
}
this.#size++;
}
出队操作
dequeue() {
const current = this.#head;
if (!current) {
return;
}
this.#head = this.#head.next;
this.#size--;
return current.value;
}
初始化/清空队列
clear() {
this.#head = undefined;
this.#tail = undefined;
this.#size = 0;
}
获取队列大小
get size() {
return this.#size;
}
遍历队列
设置Symbol.iterator字段使得该函数的实例对象可以被迭代。该函数用 generator 来实现迭代,便于控制迭代顺序。
* [Symbol.iterator]() {
let current = this.#head;
while (current) {
yield current.value;
current = current.next;
}
}
总结
1.Symbol.iterator 的作用有三个: 一是为各种数据结构,提供一个统一的、简便的访问接口;二是使得数据结构的成员能够按某种次序排列;三是 ES6 创造了一种新的遍历命令for...of循环,Iterator 接口主要供for...of消费。