class ArrayList < T > {
private arrayList: (T | number)[] = [];
add(indexOrValue: T | number, value ? : T) {
if (value !== undefined) {
//타입가드
if (typeof indexOrValue === "number") {
this.arrayList.splice(indexOrValue, 0, value);
}
} else {
this.arrayList.push(indexOrValue);
}
}
remove(index: number) {
this.arrayList.splice(index, 1);
}
addAll(elements: T[]) {
this.arrayList = [...this.arrayList, ...elements];
}
get(index: number): T | number {
return this.arrayList[index];
}
clear() {
this.arrayList = [];
}
isEmpty(): boolean {
return this.arrayList.length === 0 ? true : false;
}
set(index: number, value: T) {
// this.arrayList.splice(index, 0, value);
this.arrayList[index] = value;
}
toArray(): (T | number)[] {
return this.arrayList;
}
size(): number {
return this.arrayList.length;
}
}
let aList = new ArrayList<string>();
aList.add("a");
aList.add("b");
aList.add("c");
console.log("1번 add : ", aList.toArray());
aList.add(1, "hi");
console.log("2번 index로 add : ", aList.toArray());
aList.remove(1);
console.log("3번 remove(1) : ", aList.toArray());
aList.addAll(["d", "e"]);
console.log("4번 addAll : ", aList.toArray());
console.log("5번 get(2) : ", aList.get(2));
console.log("6번 size() : ", aList.size());
aList.clear();
console.log("7번 size() after clear() : ", aList.size());
if(aList.isEmpty()) {
console.log("8번 empty !");
}
타입스크립트 퀵스타트 책을 보면서 공부중입니다.
책의 예제와 같이 제네릭을 이용한 ArrayList 자료구조 구현을 따라하였습니다.
'프로그래밍 > Javascript' 카테고리의 다른 글
forEach를 중간에 멈출 수는 없다 (0) | 2021.01.24 |
---|---|
크롬 익스텐션 개발 참고용 자료 (0) | 2020.11.18 |
Node.js에서 로그 기록하기 (0) | 2020.11.06 |
우분투(데비안) cli 환경에서 puppeteer 사용하기 (0) | 2019.08.07 |
Office UI Fabric (0) | 2018.12.23 |