源码共读03 yocto-queue

45 阅读1分钟

源码地址:github

功能介绍:一个简单的先进先出队列,只有插入推出统计个数功能,效率比Array高,时间复杂度为O(1)

核心源码:

// 节点类
class Node {
        // 当前值
	value;
        // 下一项值
	next;
        // 构造函数
	constructor(value) {
		this.value = value;
                // 默认next为空
	}
}

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
	* [Symbol.iterator]() {
		let current = this.#head;
               
		while (current) {
			yield current.value;
			current = current.next;
		}
	}
}

知识点:

生成器函数 function *

迭代函数标识符 Symbol.iterator

队列数据结构,先进先出

访问器属性:在对象属性前面加个get标识符代表是访问器属性,可以直接对size取值,不用执行size()函数

延伸知识点,设置器属性,对应是set标识符,可以直接对属性等号赋值,具体操作如下:

let test =  {
    tSize: 1,
    get size() {
        return this.tSize;
    },
    set size(tSize) {
        this.tSize = tSize;
    }
}
console.log(test.size); // 输出: 1
test.size = 2;
console.log(test.size); // 输出: 2