Javascript 队列 Queue封装

队列

队列遵循(先入先出原则),通俗的讲就是 尾部入队,对头出队。其应用场景主要是涉及到排队机制,且先排队者先完成,才能到下一个,依次到完成所有
代码实现
/**
 * 队列。  此队列外部可直接修改 instance.items
 */
/* class Queue {

    items = []
    add(el) {
        this.items.push(el)
    }
    remove() {
        return this.items.shift()
    }
    size() {
        return this.items.length
    }
    front() {
        return this.items.at(0)
    }
    isEmpty() {
        return this.items.length === 0
    }

} */
/**
 * 队列。 私有化items , # 标记形式
 */
/* class Queue {

    #items = []
    add(el) {
        this.#items.push(el)
    }
    remove() {
        return this.#items.shift()
    }
    size() {
        return this.#items.length
    }
    front() {
        return this.#items.at(0)
    }
    isEmpty() {
        return this.#items.length === 0
    }

} */
/**
 * 队列,删除对头会改变索引位置。以下为不改变索引删除,借助对象索引key 形式
 */
class Queue {

    #items = {}
    addIndex = 0
    removeIndex = 0
    add(el) {
        this.#items[this.addIndex] = el
        this.addIndex ++
    }
    remove() {
        if (this.isEmpty()) {
            return undefined
        }
        let el = this.#items[this.removeIndex]
        delete this.#items[this.removeIndex]
        this.removeIndex ++
        return el
    }
    size() {
        return this.addIndex - this.removeIndex
    }
    front() {
        return this.#items[this.removeIndex]
    }
    isEmpty() {
        return this.size() === 0
    }
    clear() {
        this.#items = {}
        this.addIndex = 0
        this.removeIndex = 0
    }

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容