CodeBlanks Logo Icon CodeBlanks

Completion

Learn to mark a task as completed.

The completeTodo function

completeTodo finds a task by id and sets its status to "completed". The task is not removed from the list; only its state changes. We find the task with find and check its existence with if.

function completeTodo(todos: Todo[], id: string): void {
  const todo = todos.find(t => t.id === id);
  if (todo) {
    todo.status = "completed";
  }
}

Toggle to reverse

To reverse a task's state you can write toggleTodo. If the task is "active" it becomes "completed"; if "completed" it becomes "active". This is useful for reopening a task.

function toggleTodo(todo: Todo): void {
  if (todo.status === "active") {
    todo.status = "completed";
  } else {
    todo.status = "active";
  }
}

Practice Write the completeTodo function

Define Status and Todo. Write addTodo and listTodos functions. Write a function completeTodo(todos: Todo[], id: string): void: find the task with find, and if it exists set its status to "completed". Add a "Süt al" task, complete it with id "1", and list them.

Starter code

index.ts
// Status ve Todo tanımla
// addTodo ve listTodos fonksiyonlarını yaz
// completeTodo(todos: Todo[], id: string): void yaz
// id'ye göre görevi bul ve status'ü "completed" yap
// bir görev ekle, tamamla ve listele

Sample solution

index.ts
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 listTodos(todos: Todo[]): void {
  todos.forEach(t => console.log(t.id + ": " + t.title + " [" + t.status + "]"));
}

const todos: Todo[] = [];
addTodo(todos, "Süt al");
completeTodo(todos, "1");
listTodos(todos);

Expected output

1: Süt al [completed]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is done to the status field to complete a task?

  • Deleted
  • Set to "completed" Correct answer
  • title is changed
  • Set to "active"

Explanation: Completing a task means setting its status field to "completed". The task is not deleted; the title is not changed.

2 Complete the find condition

Question
const todo = todos.find(t => t.id === ____);
Answer
const todo = todos.find(t => t.id === id);

Explanation: You find the task by id: t.id === id. title is not a parameter, status is of type Status (not string), and t is a Todo object.

3 Completion parts

Term Meaning
completeTodo Complete a task
todos.find(...) Find by id
todo.status = "completed" Update status
toggleTodo Toggle status

All lessons in Beginner