DEV Community

CoffeeBeagle
CoffeeBeagle

Posted on

TypeScript Queue

I wanted to use queue in TypeScript.

export class Queue<T> {
  public constructor(
    private items: T[] = []
  ) {
  }

  public enqueue(v: T) {
    this.items.push(v)
  }

  public dequeue(): T | undefined {
    if (this.items.length < 0) {
      return undefined;
    }

    const result = this.items[0];
    this.items = this.items.slice(1,);
    return result;
  }

  public peek(): T | undefined {
    if (this.items.length < 0) {
      return undefined;
    }

    return this.items[0];
  }

  public clear() {
    this.items = [];
  }

  public size() {
    return this.items.length
  }
}
Enter fullscreen mode Exit fullscreen mode

Gist

Top comments (0)