skip to Main Content

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


  1. 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:

    const tasks = [
      { type: 'critical', value: 'production issue' },
      { type: 'high', value: 'server down' },
      { type: 'medium', value: 'backup not taken' },
    ];
    
    const priority = ['critical', 'high', 'medium'];
    
    let priorityTask = tasks.find(task => priority.includes(task.type));
    
    console.log('priorityTask:', priorityTask);
    

    In this refactored code, the priority array defines the order of priority for task types. The find method is used to find the first task in the tasks array whose type is included in the priority array. This approach makes the code more scalable and easier to maintain, especially when you have a larger set of task types.

    Login or Signup to reply.
  2. const priority = ['critical', 'high', 'medium'];
    let priorityTask = priority.map(p => tasks.find(task => task.type === p)).find(task => task !== undefined);
    
    console.log('priorityTask:', priorityTask);
    

    Using the priority array we define a sort of hierarchy and find will return the first occurence, so your desired output.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search