|
| 1 | +export interface Todo { |
| 2 | + readonly id: number |
| 3 | + readonly text: string |
| 4 | + readonly completed: boolean |
| 5 | +} |
| 6 | + |
| 7 | +export class TodoRepository { |
| 8 | + readonly todos: Array<Todo> = [ |
| 9 | + { id: 1, text: "Finish homework", completed: false }, |
| 10 | + { id: 2, text: "Buy groceries", completed: false }, |
| 11 | + { id: 3, text: "Write report", completed: false }, |
| 12 | + { id: 4, text: "Clean house", completed: false }, |
| 13 | + { id: 5, text: "Pay bills", completed: false } |
| 14 | + ] |
| 15 | + |
| 16 | + get(id: number): Todo | undefined { |
| 17 | + return this.todos.find((todo) => todo.id === id) |
| 18 | + } |
| 19 | + |
| 20 | + getAll(): ReadonlyArray<Todo> { |
| 21 | + return this.todos |
| 22 | + } |
| 23 | + |
| 24 | + create(text: string): Todo { |
| 25 | + const maxId = this.todos.reduce((max, todo) => todo.id > max ? todo.id : max, 0) |
| 26 | + const newTodo = { id: maxId + 1, text, completed: false } |
| 27 | + this.todos.push(newTodo) |
| 28 | + return newTodo |
| 29 | + } |
| 30 | + |
| 31 | + update(id: number, props: Partial<Omit<Todo, "id">>): Todo | undefined { |
| 32 | + const todo = this.todos.find((todo) => todo.id === id) |
| 33 | + if (todo) { |
| 34 | + Object.assign(todo, props) |
| 35 | + return todo |
| 36 | + } |
| 37 | + return undefined |
| 38 | + } |
| 39 | + |
| 40 | + delete(id: number): boolean { |
| 41 | + const initialLength = this.todos.length |
| 42 | + this.todos.filter((todo) => todo.id !== id) |
| 43 | + return this.todos.length < initialLength |
| 44 | + } |
| 45 | +} |
0 commit comments