I have following array with three elements:
const tasks = [{
type: 'critical',
value: 'production issue',
}, {
type: 'high',
value: 'server down'
}, {
type: 'medium',
value: 'backup not taken'
}];
Now I declare an empty array which should return an element based on the priority
let priorityTask = [];
Now, the priority task should return { type: 'critical', value: 'production issue' }
since critical type would have highest priority.
If critical type is not available in the array of tasks then it should return { type: 'high', value: 'server down' }
as high type would have second priority and like wise.
I have written the following code to get the output which looks just fine But, if we have a large set of array of tasks ? how can we refactor the code to make it better.
Priority Order: Critical – High – Medium
const criticalIndex = tasks.findIndex((task) => task.type === 'critical');
const highIndex = tasks.findIndex((task) => task.type === 'high');
const mediumIndex = tasks.findIndex((task) => task.type === 'medium');
tasks.forEach((task) => {
if (criticalIndex >= 0) {
task.type === 'critical' ? priorityTask = task : [];
} else {
if (highIndex >= 0) {
task.type === 'high' ? priorityTask = task : [];
} else {
if (mediumIndex >= 0) {
task.type === 'medium' ? priorityTask = task : [];
}
}
}
});
console.log('priorityTask: ', priorityTask);
{
type: 'critical',
value: 'production issue'
}
2
Answers
You can simplify and generalize the code by using a priority array that defines the order of priority for task types. Here’s how you can refactor the code:
In this refactored code, the
priority
array defines the order of priority for task types. Thefind
method is used to find the first task in thetasks
array whose type is included in thepriority
array. This approach makes the code more scalable and easier to maintain, especially when you have a larger set of task types.Using the
priority
array we define a sort of hierarchy and find will return the first occurence, so your desired output.