Strategies for simplifying this extensive if/else block

My current if/else statement in React Native is functional but seems verbose. I am curious to know how other developers would optimize and shorten it.

I feel like my code represents a beginner's approach, and I welcome suggestions on how to improve it.

Just to clarify, I am working with React Native for this project.

getBatteryIcon() {
    if (this.props.batteryLevel >= 81 && this.props.batteryLevel <= 100) {
      return (
        <Image
          source={require('./../../../android/app/src/main/res/drawable/batterylevel_four.png')}
        />
      )
    } else if (this.props.batteryLevel >= 51 && this.props.batteryLevel <= 80) {
      return (
        <Image
          source={require('./../../../android/app/src/main/res/drawable/batterylevel_three.png')}
        />
      )
    } else if (this.props.batteryLevel >= 25 && this.props.batteryLevel <= 50) {
      return (
        <Image
          source={require('./../../../android/app/src/main/res/drawable/batterylevel_two.png')}
        />
      )
    } else {
      return (
        <Image
          source={require('./../../../android/app/src/main/res/drawable/batterylevel_one.png')}
        />
      )
    }
  }

Answer №1

When utilizing if/else if statements and returning within each block, it is possible to streamline the conditions by eliminating those that are guaranteed to be false:

if (this.props.batteryLevel >= 81) { 
  return (
    <Image
      source={require('./../../../android/app/src/main/res/drawable/batterylevel_four.png')}
    />
  )
} else if (this.props.batteryLevel >= 51) { 
  return (
    <Image
      source={require('./../../../android/app/src/main/res/drawable/batterylevel_three.png')}
    />
  )
} else if (this.props.batteryLevel >= 25) {
  return (
    <Image
      source={require('./../../../android/app/src/main/res/drawable/batterylevel_two.png')}
    />
  )
} else {
  return (
    <Image
      source={require('./../../../android/app/src/main/res/drawable/batterylevel_one.png')}
    />
  )
}

Alternatively, you can implement a loop through a list of thresholds:

const batteryLevels = [
    {level: 81, source: require("./../../../android/app/src/main/res/drawable/batterylevel_four")},
    {level: 51, source: require("./../../../android/app/src/main/res/drawable/batterylevel_three")},
    {level: 25, source: require("./../../../android/app/src/main/res/drawable/batterylevel_two")},
    {level: 0,  source: require("./../../../android/app/src/main/res/drawable/batterylevel_one")}
];

The code would then be simplified to:

let {source} = batteryLevels.find(({level}) => this.props.batteryLevel >= level);
return (
  <Image
    source={source}
  />
);

Note: If this.props.batteryLevel will always be >= 0, consider using level: -Infinity for the last threshold.


In a more general scenario (not applicable to React Native due to restrictions on require), filename handling can be abstracted as follows:

// NOT APPLICABLE TO REACT NATIVE

let level;
if (this.props.batteryLevel >= 81) { 
  level = "four";
} else if (this.props.batteryLevel >= 51) { 
  level = "three";
} else if (this.props.batteryLevel >= 25) { 
  level = "two";
} else {
  level = "one";
}
return (
  <Image
    source={require(`./../../../android/app/src/main/res/drawable/batterylevel_${level}.png`)}
  />
);

Answer №2

    let batteryStatus;
var getBatteryImage = function (batteryPercentage) {
    const level = batteryPercentage;
    switch (true) {
        case (level > 80):
            batteryStatus = '/battery_full.png';
            break;
        case (level > 50):
            batteryStatus = '/battery_half.png';
            break;
        case (level > 24):
            batteryStatus = '/battery_low.png';
            break;
        default:
            batteryStatus = 'battery_empty.png';
            break;
    }

    return './../../../android/app/src/main/res/drawable' + batteryStatus;
}

console.log(getBatteryImage(55));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

There seems to be an issue with the functionality of the AJAX file upload feature in

I've developed a method for file uploading using AJAX technology (pure JavaScript) in CodeIgniter. Here's how it works: 1- I created a script.js file to manage the AJAX/JavaScript upload process. 2- I implemented a controller in CodeIgniter to ...

The validation of form.$invalid appears to be malfunctioning when using the Angular UI date picker

There are two fields on the form, one for selecting a due date and another for entering a number. The due date field is a date picker where you can choose a date or manually enter a number to set the date. The create button gets enabled only when setting ...

Exploring Angular's capabilities with filtering and handling $http promises

Having an issue with filtering data from a JSON file that contains an array of 20 objects. Within my factory, I have implemented two functions: function fetchData() { return $http .get('mock.json') .success(_handleData) ...

The scrolling feature in the option list for Adobe Air Client and Javascript appears to be non-functional

I am currently utilizing Air Client in conjunction with HTML, CSS and Javascript. My goal is to enable scrolling through the option list using the up and down arrow keys. However, I have encountered an issue where the scrollbar does not scroll all the way ...

Positioning a dropdown menu on top of a Google Map in React with JavaScript: Best Practices

I've been attempting to place a dropdown menu at a specific location on my Google Map, specifically in the top right (or top left is also acceptable). Below is the current output I am seeing: Here is the expected result: Modifications After trying ...

The oninput() event does not trigger on phones and tablets

Currently, I am in the process of developing an application using PhoneGap. An issue has arisen where my code runs perfectly fine when tested on a browser, but the onInput() function does not seem to trigger on mobile devices. <div class="t1">09< ...

Tips for verifying login credentials with MongoDB and Express: Leveraging db.collection().findOne() or .find() functions

I am encountering an issue with a POST request involving user credentials being sent from a Login page to the API Server. The code looks like this: loginUser(creds) { //creds is in the form of { username: bob, password: 123 } var request = { ...

Iterate over a JSON document, insert an item, and then store the updated data in a separate

My JSON file contains elements like this: var data=[{ "Name": "Jeff", "Age": 35 }, { "Name": "cliff", "Age": 56 }] I need to include a new field called 'Country'. So the updated structure should be: var data=[{ "Name": "Jef ...

Ensure that selected options are unique across multiple selections

Could you help me with a question that involves matching pairs of words in both Russian and English? <div class="form-group" id="question4"> <label for="q4FirstSelectEN">4</label> <div class="row"> <div class="col-lg ...

Having trouble with the active class in vue-router when the route path includes "employees/add"?

I'm currently developing a project using Vue and implementing vue-router for navigation. A peculiar behavior occurs when the route changes to /employees - only the Employees menu item is activated. However, when the route switches to /employees/add, b ...

How can Redux help persist input value through re-rendering?

Handling Input Value Persistence in Redux despite Re-rendering? I am currently able to store and save input values, but only the data from one step ago. For example, when I click on the second input field, it displays the value from the first input fiel ...

What is the best way for the new context API to integrate with the React Native navigator?

I developed a multi-screen application with React Navigator based on the following code snippet: import { createStackNavigator, } from 'react-navigation'; const App = createStackNavigator({ Home: { screen: HomeScreen }, Profile: { screen: ...

Interactive Icon Feature Instead of Annoying Pop-Ups in JavaScript

Hello there! I need assistance fixing a code issue. Currently, the code automatically pops up when the page is opened. Is there a way to make it clickable instead of popping up automatically? <script type="text/javascript" src="//www.klaviyo.com/media/ ...

Transferring data between modules using Ajax or services in React.js

I have a React application where I need to pass data received in one component to another. After receiving the data successfully, I set the state and then try to pass this data as a property to the next component. However, when I try to access this passed ...

Adding a tooltip with a date format to a Highchart graph

Hey everyone, I'm currently working with a Highchart and I want to customize the tooltip value in a specific format. My categories and series are structured as follows: {"Categories":["2015-11-09","2015-11-08""2015-11-15"],"Series":[2,0,2]} Current ...

The onchange event does not seem to be functioning as expected in a dropdown menu that was dynamically added from a separate

Is there a way to display a list of tables from a database in a dropdown menu and allow users to select a table name? When a user selects a table name, I would like to show all the data associated with that table. The HTML file structure is as follows: & ...

When using Selenium to locate an element, it appears to be returning an unexpected empty object

This question has been bothering me for quite some time. I am currently using Selenium in conjunction with Python to find an element within a webpage. The specific element I am targeting is as follows: <a id="topmenu_adhocQtraditional_Reports" ...

Having trouble with playing audio from an array in Javascript

I've been working on creating a Drum Kit website. My approach involves using an array to hold all the sound files, and using a loop to call the play() function. However, I encountered an issue when trying to load the sounds - the debug console showed: ...

In JavaScript, the gallery feature with Lightbox effect creates a unique touch as only half of the screen fades to black in

Hello everyone, I'm a complete beginner when it comes to programming so please be gentle with me on my first question :) I'm trying to put together a simple website with a lightbox gallery, and you can check out what I have so far here. The prob ...

Mapping out your data effectively requires following the correct steps to ensure accuracy and clarity

My goal is to display a map using Mapbox only once the data is ready. The Vuex store code I am working with is as follows: /store/index.js import Vue from "vue"; import Vuex from "vuex"; import _ from "lodash"; import { bac ...