首页 > 解决方案 > How to write this statement without if/else?

问题描述

So my company is moving to this hyper functional programming forbidding if/else and nested ternary. The function is this:

const getUrlData = (url) => {
        if (!url) {
            return { finUrl: url, newTab: false };
        } else {
            if (url.startsWith("~")) {
                return { finUrl: url.substring(1), newTab: true };
            } else {
                return { finUrl: url, newTab: false };
            }
        }
    };

How could I do this same without if's/elses and nested ternary so the code doesn't look like #@$%@@? For now it's a puzzle for me, I can't solve.

标签: javascriptfunctional-programming

解决方案


首先,让我们通过反转 if 并实现其中 2 条路径返回相同的响应来简化代码:

const getUrlData = (url) => {
    if (url && url.startsWith("~")) {
        return { finUrl: url.substring(1), newTab: true };
    }
    return { finUrl: url, newTab: false };
};

现在很明显如何只使用一个三元表达式:

const getUrlData = (url) => (url && url.startsWith("~"))
                   ? { finUrl: url.substring(1), newTab: true }
                   : { finUrl: url, newTab: false };

推荐阅读