[Typescript] Queue

Using Linked list to implement a Queue.

In javascript, if you want to push a item in front of an Array, it need to shift the rest of items, not good for performance. Using Linked List is O(1) oepration for enque and deque,  which is better.

Usecase: Let's say you want to keep at most 20 items, can use a Queue

type Node<T> = {
    value: T;
    next?: Node<T>;
};

// use a linked list to implement a queue
export default class Queue<T> {
    public length: number;
    private head?: Node<T>;
    private tail?: Node<T>;

    constructor() {
        this.length = 0;
        this.head = this.tail = undefined;
    }

    enqueue(item: T): void {
        const node = { value: item };
        this.length++;
        if (!this.tail) {
            this.head = this.tail = node;
            return;
        }

        this.tail.next = node;
        this.tail = node;
    }

    deque(): T | undefined {
        if (!this.head) {
            return undefined;
        }

        this.length--;
        const head = this.head;
        this.head = this.head.next;

        // free up memory
        head.next = undefined;

        // clean up tail
        if (this.length === 0) {
            this.tail = undefined;
        }

        return head.value;
    }

    peek(): T | undefined {
        return this.head?.value;
    }
}

 

Test:

import Queue from "@code/Queue";

test("queue", function () {
    const list = new Queue<number>();

    list.enqueue(5);
    list.enqueue(7);
    list.enqueue(9);

    expect(list.deque()).toEqual(5);
    expect(list.length).toEqual(2);

    // this must be wrong..?
    debugger;

    // i hate using debuggers
    list.enqueue(11);
    debugger;
    expect(list.deque()).toEqual(7);
    expect(list.deque()).toEqual(9);
    expect(list.peek()).toEqual(11);
    expect(list.deque()).toEqual(11);
    expect(list.deque()).toEqual(undefined);
    expect(list.length).toEqual(0);

    // just wanted to make sure that I could not blow up myself when i remove
    // everything
    list.enqueue(69);
    expect(list.peek()).toEqual(69);
    expect(list.length).toEqual(1);
});

 

posted @   Zhentiw  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2022-07-19 [TypeScript] Typescript Intersection & Union Types
2022-07-19 [TypeScript] infer
2022-07-19 [Typescript] Unknow and any Types
2021-07-19 [SAA + SAP] 05. Route 53
2019-07-19 [RxJava] Composition, Run in parallel with Schedulers.io()
2018-07-19 [Vue-rx] Cache Remote Data Requests with RxJS and Vue.js
2016-07-19 [Javascript] Use Number() to convert to Number if possilbe
点击右上角即可分享
微信分享提示