yocto-queue 源码学习

48 阅读1分钟

#yocto-queue

js实现的队列,源码比较简单,会数据结构的一看就懂,包含的js知识点

  • class类
  • 生成器函数
// 节点
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;
	}
            // 遍历机制 
	* [Symbol.iterator]() {
		let current = this.#head;

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

总结

  • 利用 Symbol.iterator 支持便利机制