| 1 | // A messy project management application with tangled dependencies and responsibilities |
| 2 | // Difficulty: 5/5 |
| 3 | |
| 4 | // Global state |
| 5 | let globalTasks: any[] = []; |
| 6 | let globalUsers: any[] = []; |
| 7 | let globalProjects: any[] = []; |
| 8 | let currentUser: any = null; |
| 9 | let lastActivityTime = Date.now(); |
| 10 | let _config = { |
| 11 | maxTasksPerUser: 20, |
| 12 | maxProjectsPerUser: 5, |
| 13 | defaultPriority: "medium", |
| 14 | enableNotifications: true, |
| 15 | serverUrl: "https://api.example.com/v1", |
| 16 | }; |
| 17 | |
| 18 | // Mixed utility functions and business logic |
| 19 | const util = { |
| 20 | generateId: (prefix: string) => |
| 21 | `${prefix}_${Math.random().toString(36).substring(2, 15)}${Date.now()}`, |
| 22 | calculateProgress: (tasks: any[]) => { |
| 23 | const completed = tasks.filter((t) => t.status === "completed").length; |
| 24 | return tasks.length ? Math.round((completed / tasks.length) * 100) : 0; |
| 25 | }, |
| 26 | sendNotification: (type: string, message: string, user: any) => { |
| 27 | if (!_config.enableNotifications) return; |
| 28 | console.log(`[NOTIFICATION to ${user.email}]: ${message}`); |
| 29 | // Side effects directly inside utility function |
| 30 | if (typeof window !== "undefined") { |
| 31 | // DOM manipulation in utility |
| 32 | const notification = document.createElement("div"); |
| 33 | notification.className = `notification ${type}`; |
| 34 | notification.innerText = message; |
| 35 | document.body.appendChild(notification); |
| 36 | setTimeout(() => notification.remove(), 5000); |
| 37 | } |
| 38 | }, |
| 39 | logger: (action: string, data: any) => { |
| 40 | console.log(`[${new Date().toISOString()}] ${action}:`, data); |
| 41 | // Side effect - updating activity time |
| 42 | lastActivityTime = Date.now(); |
| 43 | }, |
| 44 | }; |
| 45 | |
| 46 | // Data validation mixed with business logic |
| 47 | function validateTask(task: any) { |
| 48 | if (!task.title) throw new Error("Task title is required"); |
| 49 | if (!task.projectId) throw new Error("Task must belong to a project"); |
| 50 | if (!globalProjects.some((p) => p.id === task.projectId)) { |
| 51 | throw new Error("Project does not exist"); |
| 52 | } |
| 53 | |
| 54 | // Validation mixed with business rules |
| 55 | const userTasks = globalTasks.filter( |
| 56 | (t) => t.assignedTo === task.assignedTo && t.status !== "completed", |
| 57 | ); |
| 58 | |
| 59 | if (userTasks.length >= _config.maxTasksPerUser) { |
| 60 | throw new Error( |
| 61 | `User cannot have more than ${_config.maxTasksPerUser} active tasks`, |
| 62 | ); |
| 63 | } |
| 64 | |
| 65 | return true; |
| 66 | } |
| 67 | |
| 68 | // Authentication mixed with data fetching |
| 69 | function authenticate(username: string, password: string) { |
| 70 | // Direct data manipulation and mocked authentication |
| 71 | const user = globalUsers.find((u) => u.username === username); |
| 72 | if (!user || user.password !== password) { |
| 73 | util.logger("auth_failed", { username }); |
| 74 | throw new Error("Invalid credentials"); |
| 75 | } |
| 76 | |
| 77 | currentUser = user; |
| 78 | util.logger("auth_success", { userId: user.id }); |
| 79 | |
| 80 | // Mixing data fetching with authentication |
| 81 | loadUserData(user.id); |
| 82 | |
| 83 | return user; |
| 84 | } |
| 85 | |
| 86 | // Data fetching with side effects |
| 87 | function loadUserData(userId: string) { |
| 88 | // This would be an API call in real app |
| 89 | console.log(`Loading data for user ${userId}`); |
| 90 | |
| 91 | // Direct global state manipulation |
| 92 | globalTasks = globalTasks.filter( |
| 93 | (t) => t.createdBy === userId || t.assignedTo === userId, |
| 94 | ); |
| 95 | |
| 96 | globalProjects = globalProjects.filter( |
| 97 | (p) => p.members.includes(userId) || p.createdBy === userId, |
| 98 | ); |
| 99 | |
| 100 | // Direct DOM manipulation |
| 101 | if (typeof document !== "undefined") { |
| 102 | const taskCount = document.getElementById("task-count"); |
| 103 | if (taskCount) { |
| 104 | taskCount.innerText = String(globalTasks.length); |
| 105 | } |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | // Task management with mixed responsibilities |
| 110 | class TaskManager { |
| 111 | // Creates a task with mixed concerns |
| 112 | createTask(taskData: any) { |
| 113 | if (!currentUser) throw new Error("Not authenticated"); |
| 114 | |
| 115 | // Authentication check mixed with business logic |
| 116 | if (taskData.projectId) { |
| 117 | const project = globalProjects.find((p) => p.id === taskData.projectId); |
| 118 | if ( |
| 119 | !project.members.includes(currentUser.id) && |
| 120 | project.createdBy !== currentUser.id |
| 121 | ) { |
| 122 | throw new Error("You do not have access to this project"); |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | const task = { |
| 127 | id: util.generateId("task"), |
| 128 | title: taskData.title, |
| 129 | description: taskData.description || "", |
| 130 | status: "new", |
| 131 | priority: taskData.priority || _config.defaultPriority, |
| 132 | createdAt: new Date(), |
| 133 | createdBy: currentUser.id, |
| 134 | assignedTo: taskData.assignedTo || currentUser.id, |
| 135 | projectId: taskData.projectId, |
| 136 | dueDate: taskData.dueDate || null, |
| 137 | comments: [], |
| 138 | attachments: [], |
| 139 | tags: taskData.tags || [], |
| 140 | timeSpent: 0, |
| 141 | lastUpdated: new Date(), |
| 142 | }; |
| 143 | |
| 144 | // Validation mixed with creation |
| 145 | validateTask(task); |
| 146 | |
| 147 | // Global state mutation |
| 148 | globalTasks.push(task); |
| 149 | |
| 150 | // Side effects - email notification mixed with task creation |
| 151 | if (task.assignedTo !== currentUser.id) { |
| 152 | const assignee = globalUsers.find((u) => u.id === task.assignedTo); |
| 153 | if (assignee) { |
| 154 | console.log( |
| 155 | `Sending email to ${assignee.email} about new task assignment`, |
| 156 | ); |
| 157 | util.sendNotification( |
| 158 | "task_assigned", |
| 159 | `You've been assigned a new task: ${task.title}`, |
| 160 | assignee, |
| 161 | ); |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | // More side effects - updating project data |
| 166 | if (task.projectId) { |
| 167 | const project = globalProjects.find((p) => p.id === task.projectId); |
| 168 | if (project) { |
| 169 | project.taskCount = (project.taskCount || 0) + 1; |
| 170 | project.lastActivity = new Date(); |
| 171 | // Recalculating project progress on each task addition |
| 172 | const projectTasks = globalTasks.filter( |
| 173 | (t) => t.projectId === project.id, |
| 174 | ); |
| 175 | project.progress = util.calculateProgress(projectTasks); |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | // Logging |
| 180 | util.logger("task_created", { taskId: task.id, title: task.title }); |
| 181 | |
| 182 | return task; |
| 183 | } |
| 184 | |
| 185 | // Update task with mixed concerns |
| 186 | updateTask(taskId: string, updates: any) { |
| 187 | if (!currentUser) throw new Error("Not authenticated"); |
| 188 | |
| 189 | const taskIndex = globalTasks.findIndex((t) => t.id === taskId); |
| 190 | if (taskIndex === -1) throw new Error("Task not found"); |
| 191 | |
| 192 | const task = globalTasks[taskIndex]; |
| 193 | |
| 194 | // Permission check mixed with update logic |
| 195 | if ( |
| 196 | task.createdBy !== currentUser.id && |
| 197 | task.assignedTo !== currentUser.id && |
| 198 | !currentUser.isAdmin |
| 199 | ) { |
| 200 | throw new Error("You do not have permission to update this task"); |
| 201 | } |
| 202 | |
| 203 | // Status transition logic mixed with update |
| 204 | if (updates.status && updates.status !== task.status) { |
| 205 | if (task.status === "completed" && updates.status !== "completed") { |
| 206 | // Re-opening completed task |
| 207 | task.reopenCount = (task.reopenCount || 0) + 1; |
| 208 | util.logger("task_reopened", { taskId, previousStatus: task.status }); |
| 209 | } |
| 210 | |
| 211 | if (updates.status === "completed") { |
| 212 | // Completing task |
| 213 | task.completedAt = new Date(); |
| 214 | task.completedBy = currentUser.id; |
| 215 | |
| 216 | // Side effect - updating user stats |
| 217 | const user = globalUsers.find((u) => u.id === currentUser.id); |
| 218 | if (user) { |
| 219 | user.completedTasks = (user.completedTasks || 0) + 1; |
| 220 | // More side effects - achievement system |
| 221 | if ( |
| 222 | user.completedTasks >= 10 && |
| 223 | !user.achievements?.includes("productive") |
| 224 | ) { |
| 225 | user.achievements = [...(user.achievements || []), "productive"]; |
| 226 | util.sendNotification( |
| 227 | "achievement", |
| 228 | "You earned the Productive badge!", |
| 229 | user, |
| 230 | ); |
| 231 | } |
| 232 | } |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | // Main update logic - directly modifying the object |
| 237 | Object.keys(updates).forEach((key) => { |
| 238 | // Skip protected fields |
| 239 | if (!["id", "createdAt", "createdBy"].includes(key)) { |
| 240 | task[key] = updates[key]; |
| 241 | } |
| 242 | }); |
| 243 | |
| 244 | task.lastUpdated = new Date(); |
| 245 | |
| 246 | // Validation after update (inconsistent) |
| 247 | validateTask(task); |
| 248 | |
| 249 | // Update global state |
| 250 | globalTasks[taskIndex] = task; |
| 251 | |
| 252 | // More side effects - project update |
| 253 | if (task.projectId) { |
| 254 | const project = globalProjects.find((p) => p.id === task.projectId); |
| 255 | if (project) { |
| 256 | const projectTasks = globalTasks.filter( |
| 257 | (t) => t.projectId === project.id, |
| 258 | ); |
| 259 | project.progress = util.calculateProgress(projectTasks); |
| 260 | project.lastActivity = new Date(); |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | // Notification side effects |
| 265 | if (updates.assignedTo && updates.assignedTo !== task.assignedTo) { |
| 266 | const assignee = globalUsers.find((u) => u.id === updates.assignedTo); |
| 267 | if (assignee) { |
| 268 | util.sendNotification( |
| 269 | "task_assigned", |
| 270 | `You've been assigned to task: ${task.title}`, |
| 271 | assignee, |
| 272 | ); |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | util.logger("task_updated", { taskId, changes: Object.keys(updates) }); |
| 277 | |
| 278 | return task; |
| 279 | } |
| 280 | |
| 281 | // Delete task with side effects |
| 282 | deleteTask(taskId: string) { |
| 283 | if (!currentUser) throw new Error("Not authenticated"); |
| 284 | |
| 285 | const taskIndex = globalTasks.findIndex((t) => t.id === taskId); |
| 286 | if (taskIndex === -1) throw new Error("Task not found"); |
| 287 | |
| 288 | const task = globalTasks[taskIndex]; |
| 289 | |
| 290 | // Permission check |
| 291 | if (task.createdBy !== currentUser.id && !currentUser.isAdmin) { |
| 292 | throw new Error("Only the creator or an admin can delete a task"); |
| 293 | } |
| 294 | |
| 295 | // Side effects before deletion |
| 296 | if (task.projectId) { |
| 297 | const project = globalProjects.find((p) => p.id === task.projectId); |
| 298 | if (project) { |
| 299 | project.taskCount = Math.max(0, (project.taskCount || 0) - 1); |
| 300 | project.lastActivity = new Date(); |
| 301 | // More side effects - recalculating metrics |
| 302 | setTimeout(() => { |
| 303 | const projectTasks = globalTasks.filter( |
| 304 | (t) => t.projectId === project.id && t.id !== taskId, |
| 305 | ); |
| 306 | project.progress = util.calculateProgress(projectTasks); |
| 307 | }, 0); |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | // Global state mutation |
| 312 | globalTasks.splice(taskIndex, 1); |
| 313 | |
| 314 | // Notification side effects |
| 315 | if (task.assignedTo !== currentUser.id) { |
| 316 | const assignee = globalUsers.find((u) => u.id === task.assignedTo); |
| 317 | if (assignee) { |
| 318 | util.sendNotification( |
| 319 | "task_deleted", |
| 320 | `A task assigned to you was deleted: ${task.title}`, |
| 321 | assignee, |
| 322 | ); |
| 323 | } |
| 324 | } |
| 325 | |
| 326 | util.logger("task_deleted", { taskId, title: task.title }); |
| 327 | |
| 328 | return { success: true }; |
| 329 | } |
| 330 | |
| 331 | // Search with mixed concerns |
| 332 | searchTasks(criteria: any) { |
| 333 | if (!currentUser) throw new Error("Not authenticated"); |
| 334 | |
| 335 | // Filtering with complex inline logic |
| 336 | let results = globalTasks.filter((task) => { |
| 337 | // Basic visibility check |
| 338 | const isVisible = |
| 339 | task.createdBy === currentUser.id || |
| 340 | task.assignedTo === currentUser.id || |
| 341 | (task.projectId && |
| 342 | globalProjects.some( |
| 343 | (p) => |
| 344 | p.id === task.projectId && |
| 345 | (p.members.includes(currentUser.id) || p.isPublic), |
| 346 | )); |
| 347 | |
| 348 | if (!isVisible) return false; |
| 349 | |
| 350 | // Apply search criteria |
| 351 | if (criteria.status && task.status !== criteria.status) return false; |
| 352 | if (criteria.priority && task.priority !== criteria.priority) |
| 353 | return false; |
| 354 | if (criteria.assignedTo && task.assignedTo !== criteria.assignedTo) |
| 355 | return false; |
| 356 | if (criteria.projectId && task.projectId !== criteria.projectId) |
| 357 | return false; |
| 358 | |
| 359 | // Text search |
| 360 | if (criteria.searchText) { |
| 361 | const searchText = criteria.searchText.toLowerCase(); |
| 362 | const matchesTitle = task.title.toLowerCase().includes(searchText); |
| 363 | const matchesDescription = task.description |
| 364 | ?.toLowerCase() |
| 365 | .includes(searchText); |
| 366 | const matchesTags = task.tags?.some((tag: string) => |
| 367 | tag.toLowerCase().includes(searchText), |
| 368 | ); |
| 369 | |
| 370 | if (!matchesTitle && !matchesDescription && !matchesTags) return false; |
| 371 | } |
| 372 | |
| 373 | // Date filters |
| 374 | if ( |
| 375 | criteria.createdAfter && |
| 376 | new Date(task.createdAt) < new Date(criteria.createdAfter) |
| 377 | ) |
| 378 | return false; |
| 379 | if ( |
| 380 | criteria.createdBefore && |
| 381 | new Date(task.createdAt) > new Date(criteria.createdBefore) |
| 382 | ) |
| 383 | return false; |
| 384 | if ( |
| 385 | criteria.dueBefore && |
| 386 | task.dueDate && |
| 387 | new Date(task.dueDate) > new Date(criteria.dueBefore) |
| 388 | ) |
| 389 | return false; |
| 390 | if ( |
| 391 | criteria.dueAfter && |
| 392 | task.dueDate && |
| 393 | new Date(task.dueDate) < new Date(criteria.dueAfter) |
| 394 | ) |
| 395 | return false; |
| 396 | |
| 397 | return true; |
| 398 | }); |
| 399 | |
| 400 | // Sorting mixed with filtering |
| 401 | if (criteria.sortBy) { |
| 402 | results.sort((a, b) => { |
| 403 | if (criteria.sortBy === "dueDate") { |
| 404 | if (!a.dueDate) return criteria.sortDir === "asc" ? 1 : -1; |
| 405 | if (!b.dueDate) return criteria.sortDir === "asc" ? -1 : 1; |
| 406 | return criteria.sortDir === "asc" |
| 407 | ? new Date(a.dueDate).getTime() - new Date(b.dueDate).getTime() |
| 408 | : new Date(b.dueDate).getTime() - new Date(a.dueDate).getTime(); |
| 409 | } |
| 410 | |
| 411 | if (criteria.sortBy === "priority") { |
| 412 | const priorityMap: Record<string, number> = { |
| 413 | high: 3, |
| 414 | medium: 2, |
| 415 | low: 1, |
| 416 | }; |
| 417 | return criteria.sortDir === "asc" |
| 418 | ? priorityMap[a.priority] - priorityMap[b.priority] |
| 419 | : priorityMap[b.priority] - priorityMap[a.priority]; |
| 420 | } |
| 421 | |
| 422 | // Default sort by creation date |
| 423 | return criteria.sortDir === "asc" |
| 424 | ? new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime() |
| 425 | : new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(); |
| 426 | }); |
| 427 | } |
| 428 | |
| 429 | // Pagination mixed with core functionality |
| 430 | if (criteria.limit) { |
| 431 | const page = criteria.page || 1; |
| 432 | const start = (page - 1) * criteria.limit; |
| 433 | results = results.slice(start, start + criteria.limit); |
| 434 | } |
| 435 | |
| 436 | util.logger("tasks_searched", { criteria, resultCount: results.length }); |
| 437 | |
| 438 | return results; |
| 439 | } |
| 440 | } |
| 441 | |
| 442 | // Usage would be like: |
| 443 | // const tm = new TaskManager(); |
| 444 | // tm.createTask({ title: 'Implement login', projectId: 'proj_123', priority: 'high' }); |
| 445 | // tm.updateTask('task_123', { status: 'in_progress', assignedTo: 'user_456' }); |