TypeScript
Integration
Build the working Todo CLI by combining all parts.
Combine all parts
The Todo CLI has four main functions: addTodo (add), completeTodo (complete), filterByStatus (filter), listTodos (list). In a session you first add tasks, then complete some, then filter and list.
function addTodo(todos: Todo[], title: string): Todo[] { /* ... */ }
function completeTodo(todos: Todo[], id: string): void { /* ... */ }
function filterByStatus(todos: Todo[], status: Status): Todo[] { /* ... */ }
function listTodos(todos: Todo[]): void { /* ... */ }
Working example
Let's add three tasks and complete one, then filter for active and list. The completed task is not removed; it just does not appear in the filtered list.
const todos: Todo[] = [];
addTodo(todos, "Süt al");
addTodo(todos, "Ekmek al");
addTodo(todos, "Çay al");
completeTodo(todos, "1");
const active = filterByStatus(todos, "active");
listTodos(active);
Exercise Write the working Todo CLI
Define Status and Todo. Write addTodo, completeTodo, filterByStatus, and listTodos functions. Add three tasks ("Süt al", "Ekmek al", "Çay al"), complete one ("1"), filter for "active", and list them.
Show example solution
type Status = "active" | "completed";
interface Todo { id: string; title: string; status: Status; }
function addTodo(todos: Todo[], title: string): Todo[] {
const todo: Todo = { id: String(todos.length + 1), title, status: "active" };
todos.push(todo);
return todos;
}
function completeTodo(todos: Todo[], id: string): void {
const todo = todos.find(t => t.id === id);
if (todo) {
todo.status = "completed";
}
}
function filterByStatus(todos: Todo[], status: Status): Todo[] {
return todos.filter(t => t.status === status);
}
function listTodos(todos: Todo[]): void {
todos.forEach(t => console.log(t.id + ": " + t.title + " [" + t.status + "]"));
}
const todos: Todo[] = [];
addTodo(todos, "Süt al");
addTodo(todos, "Ekmek al");
addTodo(todos, "Çay al");
completeTodo(todos, "1");
const active = filterByStatus(todos, "active");
listTodos(active);
Test yourself
-
What is the basic flow of a Todo CLI?
- List → delete → add
- Add → complete → filter → list
- Filter → add → complete
- Complete → list → add
Show answer
Add → complete → filter → list — You first add tasks, then complete some, then filter by status and list. This order makes a sensible CLI session.
-
Complete the filter call
const active = ____(todos, "active");
Show answer
const active = filterByStatus(todos, "active");
-
Integration flow
- addTodo
- First step: add
- completeTodo
- Second step: complete
- filterByStatus
- Third step: filter
- listTodos
- Last step: list
Next lesson: Book model