我正在编写代码来找到合适的目标并对其进行后续操作。我当前的代码将首先尝试查找类型 1。如果它不存在,我将尝试查找类型 2,依此类推。因为 find 函数消耗 CPU 太多,所以我想避免一开始就使用它来查找所有类型。以下是我当前的代码。我怎样才能简化它们?
const target1 = find1(Type1);
if(target1){
operate1(target1);
}else{
const target2 = find2(Type2);
if(target2){
operate2(target2);
}else{
const target3 = find3(Type3);
if(target3){
operate3(target3);
}else{
...
}
}
}
const candidates = [
() => find1(Type1),
() => find2(Type2),
() => find3(Type3)
];
const target = candidates.reduce((t, f) => t || f(), null);
说明:创建一个函数列表,在调用时返回您的值。遍历列表,逐个执行每个函数,直到找到第一个真值并使用它。这是通过 Array.prototype.reduce
t
(最初为
null
),要么执行下一个函数并返回its 值。