Standard Stack

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

export default class Stack<T> {
  private _elements: T[]

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

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

  pop() {
    if (this.isEmpty()) {
      return null
    }
    return this._elements.pop()
  }

  peek() {
    if (this.isEmpty()) {
      return null
    }
    return this._elements[this._elements.length - 1]
  }

  size() {
    return this._elements.length
  }

  clear() {
    this._elements = []
  }

  isEmpty() {
    return this._elements.length === 0
  }
}

References

C++ STL Stack