73 lines
1.7 KiB
JavaScript
73 lines
1.7 KiB
JavaScript
/**
|
|
* @typedef {Object} Todo
|
|
* @property {number} id - Todo unique identifier
|
|
* @property {string} text - Todo text content
|
|
* @property {boolean} completed - Todo completion status
|
|
*/
|
|
|
|
/**
|
|
* @typedef {Object} TodoUpdate
|
|
* @property {string} [text] - Todo text content
|
|
* @property {boolean} [completed] - Todo completion status
|
|
*/
|
|
|
|
/**
|
|
* In-memory storage for todos
|
|
* @type {Todo[]}
|
|
*/
|
|
let todos = [
|
|
{ id: 1, text: "Learn Node.js", completed: false },
|
|
{ id: 2, text: "Build an API", completed: true },
|
|
];
|
|
|
|
/**
|
|
* Get all todos
|
|
* @returns {Todo[]} Array of all todos
|
|
*/
|
|
export const getTodos = () => todos;
|
|
|
|
/**
|
|
* Add a new todo
|
|
* @param {string} text - Todo text content
|
|
* @returns {Todo} The newly created todo
|
|
*/
|
|
export const addTodo = (text) => {
|
|
/** @type {Todo} */
|
|
const newTodo = {
|
|
id: todos.length > 0 ? Math.max(...todos.map((t) => t.id)) + 1 : 1,
|
|
text,
|
|
completed: false,
|
|
};
|
|
todos.push(newTodo);
|
|
return newTodo;
|
|
};
|
|
|
|
/**
|
|
* Update a todo by ID
|
|
* @param {string} id - Todo ID to update
|
|
* @param {TodoUpdate} updates - Properties to update
|
|
* @returns {Todo | null} Updated todo or null if not found
|
|
*/
|
|
export const updateTodoById = (id, updates) => {
|
|
/** @type {number} */
|
|
const todoIndex = todos.findIndex((todo) => todo.id === parseInt(id));
|
|
if (todoIndex === -1) return null;
|
|
|
|
todos[todoIndex] = { ...todos[todoIndex], ...updates };
|
|
return todos[todoIndex];
|
|
};
|
|
|
|
/**
|
|
* Delete a todo by ID
|
|
* @param {string} id - Todo ID to delete
|
|
* @returns {boolean} True if deleted, false if not found
|
|
*/
|
|
export const deleteTodoById = (id) => {
|
|
/** @type {number} */
|
|
const todoIndex = todos.findIndex((todo) => todo.id === parseInt(id));
|
|
if (todoIndex === -1) return false;
|
|
|
|
todos.splice(todoIndex, 1);
|
|
return true;
|
|
};
|