Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

61
Views
How can I clean up this if-else function? (Javascript ES6)

I'm a beginner React developer.

I am cleaning up my codes.

I'm trying to get rid of the if-else statement as much as possible, but I don't know how to handle this function.

    const calc = () => {
        if (100 < responsiveWidth.phone) {
            setPerPage(1);
        } else if (100 < responsiveWidth.tablet) {
            setPerPage(2);
        } else if (100 < responsiveWidth.smallDesktop) {
            setPerPage(3);
        } else if (100 < responsiveWidth.desktop) {
            setPerPage(4);
        } else {
            setPerPage(6);
        }
    };

I really hate this code. Can you help me out?

7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

You could find the index (Array#findIndex) and add one.

const 
    widths = [width.phone, width.tablet, width.smallDesktop, width.desktop],
    calc = width => setPerPage(widths.findIndex(w => width < w) + 1) || 6);
7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.