개발일지

[TS] 7. 제네릭-Quiz 본문

JS, TS/[TS | 강의] TS·OOP

[TS] 7. 제네릭-Quiz

lyjin 2022. 10. 30.

22.09.08 목

  • oop-quiz stack 제네릭으로 구현해보기

 

 

interface Stack<T> {
  size: number;
  push(value: T): void;
  pop(): T;
}

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

class StackImpl<T> implements Stack<T> {
  private _size: number = 0;
  private head?: StackNode<T>;

    constructor(private capacity: number) {}

  // getter
  get size() {
    return this._size;
  }

  push(value: T) {
        if (this.size === this.capacity) {
        throw new Error('Stack is full!');
      }

    const node = { // 명확한 타입 존재할 경우 타입 추론 이용
      value: value,
      next: this.head,
    };

    this.head = node;
    this._size++;
  }

  pop(): T {
    if (this.head == null) {
      throw new Error('Stack is empty!');
    }

    const node = this.head;
    this.head = node.next;
    this._size--;

    return node.value;
  }
}

const strStack = new StackImpl<string>(10);
strStack.push('Ellie');
strStack.push('Bob');

const numStack = new StackImpl<number>(10);
numStack.push(1);
numStack.push(2);