Standard Queue

TypeScript implementation of queue data structure from GCC's standard library for C++.

export default class Queue<T> {
  private _elements: T[]
  private _offset: number

  constructor(elements?: T[]) {
    this._elements = elements ?? []
    this._offset = 0
  }

  enqueue(element: T) {
    this._elements.push(element)
    return this
  }

  dequeue() {
    if (this.size() === 0) {
      return null
    }

    const first = this.front()
    this._offset += 1

    if (this._offset * 2 < this._elements.length) {
      return first
    }

    this._elements = this._elements.slice(this._offset)
    this._offset = 0
    return first
  }

  front() {
    if (this.size() > 0) {
      return this._elements[this._offset]
    }
    return null
  }

  back() {
    if (this.size() > 0) {
      return this._elements[this._elements.length - 1]
    }
    return null
  }

  size() {
    return this._elements.length - this._offset
  }

  clear() {
    this._elements = []
    this._offset = 0
  }

  isEmpty() {
    return this.size() === 0
  }

  toArray() {
    return this._elements.slice(this._offset)
  }
}

References

C++ STL Queue