Skip to content

Commit

Permalink
Add sort command
Browse files Browse the repository at this point in the history
Allow user to sort the list base on the task's completion status.

Let's
* add SortCommand.java
* update Parser.java to include "sort"
  • Loading branch information
shunjieee committed Feb 29, 2024
1 parent 3f8ae17 commit 9ef7366
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 1 deletion.
58 changes: 58 additions & 0 deletions src/main/java/command/SortCommand.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package command;

import java.util.Comparator;

import task.Task;
import task.TaskList;

/**
* {@inheritDocs}
* Sort the tasks in the task list.
*/
public class SortCommand extends Command {
private TaskList taskList;

/**
* Creates an instance of SortCommand.
*/
public SortCommand(TaskList taskList) {
this.taskList = taskList;
}

/**
* {@inheritDocs}
* List all the tasks in the task list.
*/
@Override
public String execute() {
taskList.getList().sort(new StatusComparator());
String message = "I have sorted the task list according to the tasks' statuses.";
return message + "\n\n" + new ListCommand(taskList).execute();
}

/**
* {@inheritDoc}
*
* @return True if program will exit.
*/
@Override
public boolean isExit() {
return false;
}

static class StatusComparator implements Comparator<Task> {
// undone status are on top of the list
@Override
public int compare(Task task1, Task task2) {
if (!task1.checkStatus() && task2.checkStatus()) {
return -1;

} else if (task1.checkStatus() && !task2.checkStatus()) {
return 1;

} else {
return task1.getTaskName().compareToIgnoreCase(task2.getTaskName());
}
}
}
}
7 changes: 6 additions & 1 deletion src/main/java/common/Parser.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import command.FindCommand;
import command.ListCommand;
import command.MarkCommand;
import command.SortCommand;
import command.UnmarkCommand;
import task.TaskList;

Expand Down Expand Up @@ -76,12 +77,16 @@ public Command parse() throws IndexOutOfBoundsException, NumberFormatException,
cmd = new FindCommand(tasks, st);
return cmd;

case "sort":
cmd = new SortCommand(tasks);
return cmd;

case "bye":
cmd = new ExitCommand();
return cmd;

default:
throw new DukeException("OOPS!! Pls try again. :)");
throw new DukeException("OOPS!! Pls try again, hustler. :)");
}
}
}
Expand Down

0 comments on commit 9ef7366

Please sign in to comment.