简体   繁体   中英

Switch Statement default return “Unreachable” according to ESLint

I have a function which determines the url of a button (an anchor tag) based on some provided urls by a content creator, and the userAgent of the user's device.

In this function, I have two switch statements. I first check to see what the linktype the content creator has chosen to use for a button (either a web url, or an App Store link)

If the content creator specifies an App Store link, they also provide a range of urls for multiple platforms. They don't necessarily give a link for every platform, so we have a fallback to a web url, which is also either set by the creator, or given by the back-end (the first url it can find basically)

I have a problem where the default clause within the inner switch statement is flagged as Unreachable code by ESLint.

Is ESLint wrong? or is there something I could do better?

function getButtonLink() {
    switch(this.props.linkType) {
        case 0: {  // appStore link, get the best-fit appstore link for device
            switch(this.detectUserAgent()) {
                case 1: {
                    return this.setButtonUrlProp('windows');
                }
                case 2: {
                    return this.setButtonUrlProp('android'); 
                }
                case 3: {
                    return this.setButtonUrlProp('ios');
                }
                case 4: {
                    return this.setButtonUrlProp('amazon'); 
                }
                default: {
                    return this.setButtonUrlProp('web');
                }
            }
        }
        case 1:   // web link
        default: {
            return this.props.button.urls.web;
        }
    }
}

How about:

    function getButtonLink() {
        switch(this.props.linkType) {
            case 0: // appStore link, get the best-fit appstore link for device
                var agents = ["web", "windows", "android", "ios", "amazon"];
                return this.setButtonUrlProp(
                    agents[this.detectUserAgent()] || agents[0]
                );
            }
            case 1: // web link
            default: {
                return this.props.button.urls.web;
            }
        }
    }

ESLint is not showing this warning for me. Make sure sure that the error is not caused by something else, such as detectUserAgent() never returning a value that is not 1, 2, 3 or 4?

Whatever the case, I would refactor the code so that the outer condition uses something else, such as if - else as nested switch statements can be harder to read at a glance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM