1. class TaskQueue {
  2. constructor(tasks) {
  3. this.tasks = tasks || []; // Array of tasks
  4. this.queue = [...tasks]; // Create a copy for the queue
  5. this.dryRun = true; // Default to dry-run mode
  6. this.taskIndex = 0; // index of the current task
  7. }
  8. /**
  9. * Adds a task to the queue.
  10. * @param {Function} task The task to be added.
  11. */
  12. addTask(task) {
  13. this.queue.push(task);
  14. }
  15. /**
  16. * Processes the next task in the queue.
  17. */
  18. processTask() {
  19. if (this.dryRun) {
  20. console.log("Dry run: Would execute task at index:", this.taskIndex);
  21. return;
  22. }
  23. if (this.taskIndex < this.queue.length) {
  24. const task = this.queue[this.taskIndex];
  25. console.log("Executing task:", this.taskIndex + 1); // log task index
  26. try {
  27. task(); // Execute the task
  28. } catch (error) {
  29. console.error("Error executing task:", error);
  30. }
  31. this.taskIndex++;
  32. this.processTask(); // Process the next task
  33. } else {
  34. console.log("All tasks completed.");
  35. }
  36. }
  37. /**
  38. * Sets the dry-run mode.
  39. * @param {boolean} dryRun True for dry-run, false for actual execution.
  40. */
  41. setDryRun(dryRun) {
  42. this.dryRun = dryRun;
  43. }
  44. /**
  45. * Gets the current queue.
  46. * @returns {Array<Function>} The current queue of tasks.
  47. */
  48. getQueue() {
  49. return [...this.queue]; // return a copy to prevent modification
  50. }
  51. }
  52. // Example usage:
  53. // const tasks = [
  54. // () => console.log("Task 1: Performing maintenance"),
  55. // () => console.log("Task 2: Checking system logs"),
  56. // () => console.log("Task 3: Applying security patches"),
  57. // ];
  58. // const queue = new TaskQueue(tasks);
  59. // queue.setDryRun(true); // Set to dry-run mode
  60. // queue.processTask(); // Dry run output
  61. // queue.setDryRun(false); // Set to actual execution mode
  62. // queue.processTask(); // Execute tasks

Add your comment