Home > other >  Using the same if-else logic in various functions
Using the same if-else logic in various functions

Time:10-16

I have multiple functions depending on the same if-else logic in my program. And I'm using this if-else logic inside every one of them. Since this is too much code repetition of the if-else structure, I want to turn my little program's shape into a more compact one by reducing the usage of the if-else structure.

Here is what my functions look like:

 function getBatteryColor(batteryLevel) {
    var batteryColor = '#2CB65C';
  // The if-else structure
    if (batteryLevel >= 75) {
        batteryColor = '#2CB65C';
    } else if (batteryLevel < 75 && batteryLevel > 50) {
        batteryColor = '#8FD601';
    } else if (batteryLevel <= 50 && batteryLevel > 25) {
        batteryColor = '#FFBF01';
    } else if(batteryLevel <= 25 && batteryLevel > 10) {
        batteryColor = '#FD894B';
    }else{
        batteryColor = '#FF554B';
    }
    return batteryColor;
}

function changeBatteryIcon(batteryLevel, iconId){
   // Define some battery icons
    var fullBatteryIcon = // full battery icon
    var threeQuarterIcon = // three quarter battery icon
    var halfBatteryIcon = // half battery icon
    var quarterBatteryIcon = // quarter battery icon
    var emptyBatteryIcon = // empty battery icon
    var batteryIcon;

   // Same if-else structure here
    if (batteryLevel >= 75) {
        batteryIcon = fullBatteryIcon;
    } else if (batteryLevel < 75 && batteryLevel > 50) {
        batteryIcon = threeQuarterBatteryIcon;
    } else if (batteryLevel <= 50 && batteryLevel > 25) {
        batteryIcon = halfBatteryIcon;
    } else if(batteryLevel <= 25 && batteryLevel > 10) {
        batteryIcon = quarterBatteryIcon;
    }else{
        batteryIcon = emptyBatteryIcon;
    }
    $('#'   iconId).replaceWith(batteryIcon)
}

/* .
   .
   .
   A couple of more functions like that, using the same if-else logic.
*/

What are the possible ways to reduce this if-else repetition? Can I have that if-else logic in one place (maybe in a function) and write my other functions around it? Or, maybe I could write one huge function(which might not be a good idea) to gather all the functionality of other functions inside it?

I'm kind of a rookie in javascript. I thought maybe a "promise structure | async functions" could help. But I'm not proficient in that topic too. Thank you for your help in advance.

CodePudding user response:

You could simplify the conditions and return a string which represents a state and use an object for the various values.

function getBatteryState(batteryLevel) {
    if (batteryLevel >= 75) return 'full';
    if (batteryLevel > 50) return 'moreThanHalf';
    if (batteryLevel > 25) return 'moreThanQuarter';
    if (batteryLevel > 10) return 'quarterOrLess';
    return 'empty';
}
  • Related