I’m writing codes to find a proper target and make subsequent operation on it. My current codes would first try to look for Type 1. If it doesn’t exist, I’ll try to look for Type 2 and so on. Because the find function costs CPU too much, I’d like to avoid using it to find all Types at the beginning. The following are my current codes. How can I simplify them?
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{
...
}
}
}
3
Answers
You can move this code to separate function and utilize early return:
Or if your variables/functions are really named that way, use simple loop:
Try creating a list of checks and looping through them.
This will remove nesting, but adds a loop.
Create an object with all params.
Loop and break if found.