我有以下包含三个元素的数组:
const tasks = [{
type: 'critical',
value: 'production issue',
}, {
type: 'high',
value: 'server down'
}, {
type: 'medium',
value: 'backup not taken'
}];
现在我声明一个空数组,它应该根据优先级返回一个元素
let priorityTask = [];
现在,优先级任务应该返回
{ type: 'critical', value: 'production issue' }
,因为 关键类型 将具有最高优先级。
如果关键类型在任务数组中不可用,那么它应该返回
{ type: 'high', value: 'server down' }
,因为高类型将具有第二优先级,同样如此。
我编写了以下代码来获得看起来不错的输出但是,如果我们有一大堆任务呢?我们如何重构代码以使其变得更好。
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'
}
您可以通过使用定义任务类型优先级顺序的优先级数组来简化和概括代码。以下是重构代码的方法:
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);
在此重构的代码中,
priority
数组定义了任务类型的优先级顺序。 find
方法用于查找tasks
数组中的第一个任务,其类型包含在priority
数组中。这种方法使代码更具可扩展性并且更易于维护,特别是当您有更多的任务类型时。