How to avoid deeply nested if-else in JavaScript with different, computationally expensive condition variables?

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

3

Try creating a list of checks and looping through them.
This will remove nesting, but adds a loop.

const procedures = [
  procedure1,
  procedure2,
  procedure3,
  () => {
    console.log("nothing...");
  },
];

for (let i = 0; i < procedures.length; i++) {
  if (procedures[i]()) break; // stop if procedure is done
}

function procedure1() {
  const target1 = find1(Type1);

  if (target1) {
    operate1(target1);

    return true; // notify that procedure is done
  }
}

function procedure2() {
  const target2 = find2(Type2);

  if (target2) {
    const res = operate2(target2);

    if (res === null) return false; // continue with next procedure

    // notify that procedure is done
    return true;
  }
}

function procedure3() {
  const target3 = find2(Type3);

  if (target3) {
    const res = operate3(target3);

    return true;
  }
}

1

Create an object with all params.
Loop and break if found.

const targets = [
    { type: Type1, find: find1, operate: operate1 },
    { type: Type2, find: find2, operate: operate2 },
    { type: Type3, find: find3, operate: operate3 },
    // Add more types as needed
];

let found = false;
for (const { type, find, operate } of targets) {
    const target = find(type);
    if (target) {
        operate(target);
        found = true;
        break; // Exit loop if target is found
    }
}

if (!found) {
    // Handle case when no target is found
    console.log("No target found");
}

You can move this code to separate function and utilize early return:

function findTarget()
{
    const target1 = find1(Type1);

    if(target1){
        operate1(target1);

        return;
    }

    const target2 = find2(Type2);

    if(target2){
        operate2(target2);

        return;
    }

    const target3 = find3(Type3);

    if(target3){
        operate3(target3);

        return;
    }

    ...
}

Or if your variables/functions are really named that way, use simple loop:

for (let i = 1; i <= possibleTypes; i++) {
    let target = window['find' + i](window['Type' + i])

    if (!target) {
        continue;
    }

    window['operate' + i](target);

    break;
}

1

LEAVE A COMMENT