Search code examples
javascriptfunctionif-statementcomplexity-theory

Best practice to multiple 'ifs' - Javascript


I built a function to make a responsive carousel with multiples imgs per slide. (couldn't make Owl Carousel work on my Angular project, but not the point here).

I set the amount of img that will be presented by slide based on the current screen width.

Here is my code:

   imgsHistoria = [
    "../../assets/imgs/historia/hist_01.png",
    "../../assets/imgs/historia/hist_02.png",
    "../../assets/imgs/historia/hist_03.png",
    "../../assets/imgs/historia/hist_04.png",
    "../../assets/imgs/historia/hist_05.png",
    "../../assets/imgs/historia/hist_06.png",
    "../../assets/imgs/historia/hist_07.png",
    "../../assets/imgs/historia/hist_08.png",
    "../../assets/imgs/historia/hist_09.png",
    "../../assets/imgs/historia/hist_10.png",
  ];

  imgsHistoriaArray = [];
   resizeCarousel() {
    let images = this.imgsHistory;
    let cut = this.getCut();
    this.imgsHistoryArray = [];

    for (var i = 0; i < images.length; i = i + cut) {
      this.imgsHistoryArray.push(images.slice(i, i + cut));
    }
  }

  getCut() {
    if (this.getScreenWidth < 480) {
      return 1
    } if (this.getScreenWidth < 576) {
      return 2
    } if (this.getScreenWidth < 768) {
      return 3
    } if (this.getScreenWidth < 992) {
      return 4
    }
    return 6;
  }

The thing is that I have CodeMetrics installed and it's showing that the getCut() function has complexity 10, which is not great. How can I improve this function?


Solution

  • You could use an array and a loop to reduce the number of if statements:

    getCut() {
        let widths = [480, 576, 768, 992];
        for(let i = 0; i < widths.length; i++) {
            let width = widths[i];
            if(this.getScreenWidth < width) 
                return i+1;
        }
        return 6;
    }
    

    Here we define an array containing the widths, loop through until we find the correct value, then return the corresponding number based on its index.