개발일지
[TS] 7. 제네릭-Quiz 본문
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);
'JS, TS > [TS | 강의] TS·OOP' 카테고리의 다른 글
[TS] 10. 타입스크립트의 핵심 #1 - Type과 Interface (0) | 2022.11.08 |
---|---|
[TS] 9. 에러 처리 하기 (0) | 2022.11.08 |
[TS] 6. 제네릭 (0) | 2022.10.30 |
[TS] 5. 객체지향 프로그래밍-Quiz (0) | 2022.10.30 |
[TS] 4. 객체지향 프로그래밍 (0) | 2022.10.30 |