typescript 강의 따라하기
파일구조
index.ts
import TodoItem from "./TodoItem";
import { data } from "./data";
import TodoCollection from "./TodoCollection";
const sampleTodos : TodoItem [] = data.map(
(item) => new TodoItem(item.id, item.task, item.complete)
);
const myTodoCollection = new TodoCollection("My Todo List", sampleTodos);
myTodoCollection.addTodo("JavaScript 학습하기");
myTodoCollection.addTodo("친구 만나기");
myTodoCollection.markComplete(3, true);
console.log(`${myTodoCollection.userName}`);
myTodoCollection.getTodoItems(true).forEach((item) => item.printDetails());
console.log("======================");
myTodoCollection.getTodoItems(false).forEach((item)=> item.printDetails());
data.ts
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.data = void 0;
exports.data = [
{ id: 1, task: '장보기', complete: true },
{ id: 2, task: 'TS 학습하기', complete: false },
];
TodoCollection.ts
import TodoItem from './TodoItem';
class TodoCollection {
private nextId : number = 1;
private itemMap : Map<number, TodoItem>;
constructor(public userName:string, public todoItems:TodoItem[] = []){
this.itemMap = new Map<number, TodoItem>();
todoItems.forEach((item)=> this.itemMap.set(item.id, item));
}
getTodoById(id: number) : TodoItem | undefined {
return this.itemMap.get(id); //itemMap을 추가하면서 수정
}
addTodo(task: string): number {
while(this.getTodoById(this.nextId)){
this.nextId++;
}
this.itemMap.set(this.nextId, new TodoItem(this.nextId,task));//itemMap을 추가하면서 수정
return this.nextId;
}
//includeComplete -> true : 모든 할일 목록 반환
//includecomplete -> true : 완료 목록은 제외한 할일 목록 반환
getTodoItems(includeComplete: boolean): TodoItem[] {
return[...this.itemMap.values()].filter(
(item)=> includeComplete|| !item.complete
);
}
removeComplete():void {
this.itemMap.forEach((item)=> {
if(item.complete){
this.itemMap.delete(item.id);
}
})
}
markComplete(id: number, complete: boolean) : void {
const todoItem =this.getTodoById(id);
if(todoItem){
todoItem.complete = complete;
}
}
}
export default TodoCollection;
TodoItems.ts
class TodoItem {
constructor(
public id: number,
public task: string,
public complete: boolean = false // id와 task값만 념겨주면complete는 자동으로 false로 초기화 된다.
) {
this.id = id;
this.task = task;
this.complete = complete;
}
printDetails(): void {
console.log(
`${this.id}\t${this.task}\t${this.complete ? "\t(complete)": "\t(not complete)"}` // ? 은 무엇일까 this.complete가 참이면 앞에있는 complete표시 아니라면 뒤에있는 not complete 표시
);
}
}
export default TodoItem;