interface Node<T> {
  value: T;
  prev?: Node<T>;
  next?: Node<T>;
}
export class DoubleQueue<T> {
  protected _head?: Node<T>;
  protected _tail?: Node<T>;
  protected _size = 0;
  constructor(it?: Iterable<T>) {
    if (it) {
      for (const item of it) {
        this.push(item);
      }
    }
  }
  get size() {
    return this._size;
  }
  push(item: T) {
    const node: Node<T> = { value: item };
    if (this.size) {
      (this._tail!.next = node).prev = this._tail;
      this._tail = node;
    } else {
      this._head = this._tail = node;
    }
    this._size++;
  }
  pop(): T | undefined {
    if (!this.size) return undefined;
    const node = this._tail!;
    if (this.size === 1) {
      this._head = this._tail = undefined;
    } else {
      node.prev!.next = undefined;
    }
    this._size--;
    if (this.size === 1) this._head = this._tail;
    return node.value;
  }
  unshift(item: T) {
    const node: Node<T> = { value: item };
    if (this.size) {
      (this._head!.prev = node).next = this._head;
      this._head = node;
    } else {
      this._head = this._tail = node;
    }
    this._size++;
  }
  shift(): T | undefined {
    if (!this.size) return undefined;
    const node = this._head!;
    if (this.size === 1) {
      this._head = this._tail = undefined;
    } else {
      node.next!.prev = undefined;
    }
    this._size--;
    if (this.size === 1) this._tail = this._head;
    return node.value;
  }
  get(i: number): T | undefined {
    const reversed = i < 0;
    if (i < -this.size || i >= this.size) return undefined;
    let node = reversed ? this._tail! : this._head!;
    if (reversed) i = -i - 1;
    for (let j = 1; j <= i; j++) {
      node = reversed ? node.prev! : node.next!;
    }
    return node.value;
  }
  *iter() {
    for (let node = this._head; node; node = node.next) {
      yield node.value;
    }
  }
  [Symbol.iterator]() {
    return this.iter();
  }
  *reverseIter() {
    for (let node = this._tail; node; node = node.prev) {
      yield node.value;
    }
  }
}
