Search code examples
javascriptreactjsif-statementrefactoringcode-cleanup

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?


Solution

  • 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);