-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtaskManager.js
81 lines (70 loc) · 2.26 KB
/
taskManager.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
class TaskManager {
constructor() {
// Load tasks from localStorage or initialize an empty array
this.tasks = JSON.parse(localStorage.getItem("tasks")) || [];
}
// Save tasks to localStorage
saveTasks() {
localStorage.setItem("tasks", JSON.stringify(this.tasks));
}
// Add a new task
addTask(title, description, priority, dueDate = null) {
if (!title.trim()) {
console.error("Task title cannot be empty");
return;
}
const newTask = {
id: Date.now(), // Unique ID based on timestamp
title,
description,
priority,
completed: false,
dueDate: dueDate || "No due date",
createdAt: new Date().toISOString()
};
this.tasks.push(newTask);
this.saveTasks(); // Save updated task list
}
// Delete a task by ID
deleteTask(taskId) {
this.tasks = this.tasks.filter(task => task.id !== taskId);
this.saveTasks();
}
// Update a task by ID
updateTask(taskId, updates) {
this.tasks = this.tasks.map(task =>
task.id === taskId ? { ...task, ...updates } : task
);
this.saveTasks();
}
// Toggle task completion status
toggleTaskCompletion(taskId) {
this.tasks = this.tasks.map(task =>
task.id === taskId ? { ...task, completed: !task.completed } : task
);
this.saveTasks();
}
// Filter tasks by status (all, completed, incomplete)
filterTasks(status) {
return this.tasks.filter(task =>
status === "all" ? true : task.completed === (status === "completed")
);
}
// Sort tasks by priority or date
sortTasks(by) {
if (by === "priority") {
this.tasks.sort((a, b) => a.priority.localeCompare(b.priority));
} else if (by === "date") {
this.tasks.sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt));
}
this.saveTasks();
}
// Search tasks by title
searchTasks(query) {
return this.tasks.filter(task =>
task.title.toLowerCase().includes(query.toLowerCase())
);
}
}
// Create an instance of TaskManager
const taskManager = new TaskManager();