javascriptintermediate15 minutes

Build a Todo List Manager with Filtering and Prioritization

Create a JavaScript function that manages a list of todo items, allowing for adding, removing, updating status, and filtering tasks based on their priority and completion status.

Challenge prompt

Write a function called `manageTodos` that maintains an internal list of todo items. Each todo item should have an id, description, priority (low, medium, high), and a completed status (true/false). The function should accept two arguments: a command string ('add', 'remove', 'toggle', 'filter') and a payload object that changes based on the command: - 'add': the payload includes description and priority; assign a unique id and set completed to false. - 'remove': the payload includes the id of the todo to remove. - 'toggle': the payload includes the id of the todo; toggle its completed status. - 'filter': the payload includes optional filters priority and/or completed, and returns a filtered array of todos matching these criteria. Implement proper internal state handling so repeated calls to `manageTodos` modify or query the same todo list. Example usage: manageTodos('add', { description: 'Write code', priority: 'high' }); manageTodos('toggle', { id: 1 }); manageTodos('filter', { completed: false, priority: 'high' });

Guidance

  • Use a closure or module pattern to encapsulate the todo list as a private variable.
  • Ensure unique ids are generated for each new todo item.
  • Implement the filter command to handle one or both filters gracefully.
  • Make sure to update the completed status correctly when toggling.

Hints

  • Consider using an array to store todos and find items by id using findIndex.
  • Use default parameter values to make filters optional when filtering.
  • Use a simple incremental counter or Date.now() for unique id generation.

Starter code

function manageTodos() {
  const todos = [];
  let idCounter = 1;

  return function(command, payload) {
    // Your implementation here
  };
}

const todoManager = manageTodos();

// Example calls
// todoManager('add', { description: 'Learn JavaScript', priority: 'medium' });

Expected output

[{ id: 1, description: 'Write code', priority: 'high', completed: false }]

Core concepts

closuresarraysobjectsstate management

Challenge a Friend

Send this duel to someone else and see if they can solve it.