Skip to content Skip to sidebar Skip to footer

Avoiding Several Nested If Statements

I'm writing a function that pushes specific (predefined) variables to predefined arrays based on the status of 4 variables, all of which are ranging from 1 to 5 (they are the resul

Solution 1:

Here is an example of abstracting it away using a function:

//X = the combination of A and B.//Y = the combination of C and D.//Z = the combination of A, B, C and D.// in this example:// A > 5, B > 10, C> 15, D > 20functionreturnCharacteristic(input) {
  if (input[0] > 5 && input[1] > 10 && input[2] > 15 && input[3] > 20) {
    return'Z';
  }
  if (input[2] > 15 && input[3] > 20) {
    return'Y';
  }
  if (input[0] > 5 && input[1] > 10) {
    return'X';
  }
  
  return'No criterea met';


}

let test1 = [10, 5, 33, 5];
let test2 = [10, 15, 32, 50];
let test3 = [20, 20, 10, 9];
let test4 = [0, 5, 50, 50];


console.log(returnCharacteristic(test1));
console.log(returnCharacteristic(test2));
console.log(returnCharacteristic(test3));
console.log(returnCharacteristic(test4));

In this example I used some random conditions to determine if a criteria was met but you of course need to tailor them to your needs. Usually when your code is deeply nested like yours you have made a code designing mistake. Usually there are more elegant solutions which require you to refactor the code a bit.

Deeply nesting code increases the difficulty of reasoning about it which not only makes your code less maintainable but also increases the chances of introducing bugs. And even when there are bugs it is harder to debug is deeply nested code.

Hopefully this was helpful.

Solution 2:

If i understand what you're trying to do right, i think you can do something like this

var obj = {
        "highInfluence_highRelevance": highInfluenceHighRelevance,
        "highInfluence_lowRelevance": highInfluenceLowRelevance,
        "lowInfluence_highRelevance": lowInfluenceHighRelevance,
        "lowInfluence_lowRelevance": lowInfluenceLowRelevance,
        "highMotivation_highOrientation": highMotivationHighOrientation,
        "highMotivation_lowOrientation": highMotivationLowOrientation,
        "lowMotivation_highOrientation": lowMotivationHighOrientation,
        "lowMotivation_lowOrientation": lowMotivationLowOrientation
    }

    var imgStr = "";

    functionevaluateRadioParameters(num) {
        if (num >= 3) return"high";
        elseif (num < 3) return"low";
        return"";
    }

    functionsetimgStr(num, str) {
        if (num >= 3) imgStr += "H";
        elseif (num < 3) imgStr += "L";
       elseconsole.log('problem with ' + str + '. It is = ', num);
    }

    functiongetRadioParameters(influence, relevance, motivation, orientation) {
        var influenceStr = evaluateRadioParameters(influence);
        var relevanceStr = evaluateRadioParameters(relevance);
        var motivationStr = evaluateRadioParameters(motivation);
        var orientationStr = evaluateRadioParameters(orientation);

        if (influenceStr == "" || relevanceStr == "") {
            influenceRelevanceArr.push("");
        } else {
            influenceRelevanceArr.push(obj[influenceStr + "Influence_" + relevanceStr + "Relevance"]);
        }

        if (motivationStr == "" || orientationStr == "") {
            motivationOrientationArr.push("");
        } else {
            motivationOrientationArr.push(obj[influenceStr + "Influence_" + relevanceStr + "Relevance"]);
        }

        if (influenceStr == "" || relevanceStr == "" || motivationStr == "" || orientationStr == "")
            stkImagesArr.push('');
        else {
            setimgStr(influence, "influence");
            setimgStr(relevance, "relevance");
            setimgStr(motivation, "motivation");
            setimgStr(orientation, "orientation");
            stkImagesArr.push(getImage(imgStr));
        }

    }

Solution 3:

It might be easier to get each individual value separately, then combine them somehow - it all depends on your data structures. From what I see so far, I think you can do something like this (this is high level, you'll have to fill in the full details yourself):

functiongetRadioParameters(influence, relevance, motivation, orientation) {
  const inf = gague(influence, 'highInfluence', 'lowInfluence');
  const rel = gague(relevance, 'highRelevance', 'lowRelevance');
  const mot = gague(motivation, 'highMotivation', 'lowMotivation');
  const ori = gague(orientation, 'highOrientation', 'lowOrientation');
  const allVals = [inf, rel, mot, ori];
  const finalValues = getFinalValues(allVals);

  return finalValues;
}

functiongetFinalValues(allVals) {
  const finalValues = { img: '', char: '' };

  allVals.forEach(function(item) {
    finalValues.img += item.img;
    finalValues.char += item.char;
  });

  return finalValues;
}

functiongague(param, high, low) {
  if (param >= 3) return { char: high, img: 'H' };
  return { char: low, img: 'L' };
}

let result = getRadioParameters(3, 3, 3, 3);
console.log(result);

result = getRadioParameters(3, 3, 3, 0);
console.log(result);

result = getRadioParameters(3, 3, 0, 3);
console.log(result);

result = getRadioParameters(3, 0, 3, 3);
console.log(result);

also, if you're using ES6/7 you can simplify the code even more:

functiongetRadioParameters(influence, relevance, motivation, orientation) {
  const inf = gague(influence, 'HIGH-influence', 'LOW-influence');
  const rel = gague(relevance, 'HIGH-relevance', 'LOW-relevance');
  const mot = gague(motivation, 'HIGH-motivation', 'LOW-motivation');
  const ori = gague(orientation, 'HIGH-orientation', 'LOW-orientation');
  const allVals = [inf, rel, mot, ori];
  const finalValue = allVals.reduce(getFinalValue, { img: '', char: '' });

  return finalValue;
}

functiongetFinalValue(prev, current) {
  const img = prev.img + current.img;
  const char = prev.char + ' ' + current.char;
  return { img, char };
}

functiongague(param, high, low) {
  if (param >= 3) return { char: high, img: 'H' };
  return { char: low, img: 'L' };
}

let result = getRadioParameters(3, 3, 3, 3);
console.log(result);

result = getRadioParameters(3, 3, 3, 0);
console.log(result);

result = getRadioParameters(3, 3, 0, 3);
console.log(result);

result = getRadioParameters(3, 0, 3, 3);
console.log(result);

Post a Comment for "Avoiding Several Nested If Statements"