【若川视野 x 源码共读】第32期 | yocto-queue 队列 链表

56 阅读1分钟

yocto-queue 是一个数组模拟队列,先进先出,可以查看队列排队数量的库;

//定义数据结构
class Node {
	value;
	next;

	constructor(value) {
		this.value = value;
	}
}

export default class Queue {
  //私有变量的格式
	#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;
	}

  //迭代器结合生成器  遍历 从head 开始
	* [Symbol.iterator]() {
		let current = this.#head;

		while (current) {
			yield current.value;
			current = current.next;
		}
	}
}

总结:

  • 对于class定义一个数据结构的写法有了深的了解,也觉得很新奇
  • 对class内的私有变量的引用
  • 链表的结构使用 更深的理解
  • 迭代器做遍历,结合www.yuque.com/jianlegelaj… 这一期,感觉理解起来很轻松,但是对迭代器结合生成器使用,觉得很新奇和高级,为以后使用遍历提供了一种新的思路。