Menu
Coddy logo textTech

Function to Change Task Status

Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 47 of 73.

challenge icon

Challenge

Easy

You are provided with the following from the previous challenge:

  • The Task interface with id (number), title (string), and status (literal type)
  • Three task variables: firstTask, secondTask, and thirdTask
  • The getTaskInfo function
  • The addTask function
  • The initialTasks and updatedTasks arrays

Create a function named changeTaskStatus that takes three parameters:

  • taskList of type Task[] (an array of Task objects)
  • taskId of type number (the ID of the task to update)
  • newStatus of type 'todo' | 'in-progress' | 'done' (the new status for the task)

The function should:

  • Find the task with the matching ID in the task list
  • Update that task's status to the new status
  • Return a new array with the updated task (do not modify the original array)
  • If no task with the given ID is found, return the original array unchanged

Create a variable named testTasks of type Task[] containing firstTask, secondTask, and thirdTask.

Use your changeTaskStatus function to:

  • Change the status of task with ID 1 to 'in-progress' and store the result in progressTasks
  • Change the status of task with ID 2 to 'done' in progressTasks and store the result in completedTasks

Print the following outputs on separate lines:

  • Call getTaskInfo with the first task from testTasks and print the result
  • Call getTaskInfo with the first task from progressTasks and print the result
  • Call getTaskInfo with the second task from completedTasks and print the result
  • Print the status of the first task in testTasks
  • Print the status of the second task in completedTasks

Try it yourself

interface Task {
  id: number;
  title: string;
  status: 'todo' | 'in-progress' | 'done';
}

const firstTask: Task = {
  id: 1,
  title: "Learn TypeScript interfaces",
  status: 'todo'
};

const secondTask: Task = {
  id: 2,
  title: "Build task management app",
  status: 'in-progress'
};

const thirdTask: Task = {
  id: 3,
  title: "Write unit tests",
  status: 'done'
};

function getTaskInfo(task: Task): string {
    return `Task ${task.id}: ${task.title} - ${task.status}`;
}

function addTask(taskList: Task[], title: string): Task[] {
  const newTask: Task = {
    id: taskList.length + 1,
    title: title,
    status: 'todo'
  };
  return [...taskList, newTask];
}

const initialTasks: Task[] = [firstTask, secondTask];

const updatedTasks: Task[] = addTask(initialTasks, "Review code changes");

console.log(initialTasks.length);
console.log(updatedTasks.length);
console.log(getTaskInfo(updatedTasks[updatedTasks.length - 1]));
console.log(updatedTasks[updatedTasks.length - 1].title);
console.log(updatedTasks[updatedTasks.length - 1].status);

All lessons in Introduction To TypeScript