yocto-queue 队列 链表

136 阅读1分钟

本文是对yocto-queue的学习整理,源码仓库地址:github.com/sindresorhu…

yocto-queue 是什么?

微型队列数据结构(Tiny queue data structure)

如果您在大型数组上执行大量 Array#push() 和 Array#shift(),则应该使用此包而不是数组,因为 Array#shift() 具有线性时间复杂度 O(n) 而 Queue#dequeue() 具有恒定的时间复杂度 O(1)。 这对大型阵列产生了巨大的影响。

队列是元素的有序列表,其中一个元素插入到队列的末尾并从队列的前面移除。 队列基于先进先出 (FIFO) 原则工作。

API

queue = new Queue()

该实例是一个 Iterable,这意味着您可以使用“for...of”循环从前到后遍历队列,或者使用扩展将队列转换为数组。 除非你真的需要,否则不要这样做,因为它很慢。

.enqueue(value)

向队列中添加一个值。

.dequeue()

删除队列中的下一个值。 返回已删除的值或如果队列为空,则返回undefined。

.clear()

清空队列。

.size

队列的大小。

源码

Node节点实现

class Node {
    value;// 存储当前值
    next;// 存储下一个节点指针

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

enqueue 入队

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

dequeue() {        const current = this.#head;        if (!current) {            return;        }        this.#head = this.#head.next;        this.#size--;        return current.value;    }

// 清空 clear

clear() {        this.#head = undefined;        this.#tail = undefined;        this.#size = 0;    }

// 当前队列元素个数 size

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

Iterable

* [Symbol.iterator]() {        let current = this.#head;        while (current) {            yield current.value;            current = current.next;        }    }

通过上述实现,我们可以通过for...of获取到队列中的值

const queue = new Queue();
queue.enqueue('🦄');
queue.enqueue('🌈');
console.log([...queue]); // 输出:['🦄', '🌈']

总结

通过yocto-queue源码阅读,重温了链表,队列,也学习了Symbol.iterator的应用场景。