yocto-queue 队列 链表 源码分析笔记

117 阅读2分钟

关于yocto-queue的理解

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

  1. 支持先进先出;
  2. 支持查看队列长度;
  3. 支持展开符操作,显示队列中内容;

源码分析


// Queue  实例 class;
export default class Queue {
        // 私有属性 #head、#tail、#size; ES最新语法;内部可以访问,不能删除;外部不能访问;
	#head;
	#tail;
	#size;

        // constructor 初始化时,默认清空 #head #tail # size;
	constructor() {
		this.clear();
	}

        // enqueue 入列方法;初始化第一次入列, head tail 都为 node;这样,head 的值就固定了, tail 给了next 后就可以队列继续链接了;
	enqueue(value) {
		const node = new Node(value);

		if (this.#head) {
                
                        // 上一次的tail 数据 next 值为这一次的 node; 赋值后更改了tail 的指向为新的 node;
			this.#tail.next = node;
			this.#tail = node;
		} else {
			this.#head = node;
			this.#tail = node;
		}

		this.#size++;
	}

        // 出列每次 出最前边的数据,出完后, 保存head的next为下一次的head;并减少 size;
	dequeue() {
		const current = this.#head;
		if (!current) {
			return;
		}

		this.#head = this.#head.next;
		this.#size--;
		return current.value;
	}

        // 清空所有私有属性; queue就空了;
	clear() {
		this.#head = undefined;
		this.#tail = undefined;
		this.#size = 0;
	}

	get size() {
		return this.#size;
	}

        // 每次遍历的什么 , 遍历 从head 开始, 把链表的所有next获取出来;yield返回
	* [Symbol.iterator]() {
		let current = this.#head;

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

思考

  1. * [Symbol.iterator] 这种写是 尝试过 使用别的方法名, 那么 展开获取所有数据的时候就是调用对应方法;但如果 需要默认展开操作是,* [Symbol.iterator] 是固定写法吗,与 yeild 结合;
  2. vitest 测试库, 后面需要深入学习,直到可以根据需要,应用到项目中;