How to simplify multiple if statements branches in Javascript?

  Kiến thức lập trình

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{
            ...
        }
    }
}        

1

LEAVE A COMMENT