Managing Task Status Transitions in TypeScript with Enums and Object Mapping
mark vachi
Posted on December 21, 2022
An enum in TypeScript can be used to represent the possible states of a task, as shown in the following graph:
We can use a function and an object mapping to manage transitions between these states.
enum TaskStatus {
NONE,
ACCEPT,
MEET,
REACH,
COMPLETE,
CANCEL
}
const transitionMap: { [key in TaskStatus]: TaskStatus[] } = {
[TaskStatus.NONE]: [TaskStatus.ACCEPT, TaskStatus.CANCEL],
[TaskStatus.ACCEPT]: [TaskStatus.MEET, TaskStatus.CANCEL],
[TaskStatus.MEET]: [TaskStatus.REACH, TaskStatus.CANCEL],
[TaskStatus.REACH]: [TaskStatus.COMPLETE, TaskStatus.CANCEL]
};
const transition = (currentStatus: TaskStatus, nextStatus: TaskStatus): boolean => {
return transitionMap[currentStatus].includes(nextStatus);
}
To define the valid transitions for each status, we can use an object mapping. The object keys are the current statuses, and the values are arrays of valid next statuses. We can then use the includes method to check if the desired next status is in the list of valid transitions for the current status.
Here's an example of using the transition function to check if a transition is valid:
const isValid = transition(TaskStatus.MEET, TaskStatus.REACH); // true
const isInvalid = transition(TaskStatus.MEET, TaskStatus.NONE); // false
Using this approach, we can easily manage the status transitions for our tasks and ensure that they are being updated correctly. This can be especially useful in larger projects where there may be many different states and transitions to track.
Posted on December 21, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 13, 2024
November 2, 2024