简体   繁体   English

如何在没有 if/else 的情况下编写此语句?

[英]How to write this statement without if/else?

So my company is moving to this hyper functional programming forbidding if/else and nested ternary.所以我的公司正在转向这种禁止 if/else 和嵌套三元的超功能编程。 The function is this: function 是这样的:

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 #@$%@@?如果没有if's/elses和嵌套三元组,我怎么能做到这一点,所以代码看起来不像 #@$%@@? For now it's a puzzle for me, I can't solve.现在这对我来说是一个难题,我无法解决。

First, lets simplify the code by inverting the if and realising that 2 of the paths through return the same response:首先,让我们通过反转 if 并实现其中 2 条路径返回相同的响应来简化代码:

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

It's now obvious how to use just a single ternary expression:现在很明显如何只使用一个三元表达式:

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

Using optional chaining you can rid of any condition, but you will have to transpile it somewhere to get browser support.使用可选链,您可以摆脱任何条件,但您必须将其转译到某个地方以获得浏览器支持。

const getUrlData = (url) => ({
  finUrl: url?.replace(/^~/, ''),
  newTab: !!url?.startsWith("~")
})

Transpiles to:转译为:

 const getUrlData = (url) => ({ finUrl: url === null || url === void 0? void 0: url.replace(/^~/, ''), newTab: ?:(url === null || url === void 0. void 0; url.startsWith("~")) }). console.log(getUrlData(undefined)) console.log(getUrlData('foo')) console.log(getUrlData('~bar'))

You could do something like this, splitting the function into smaller ones:你可以这样做,将 function 拆分成更小的:

const emptyUrl = (url) => ({ finUrl: url, newTab: false })

const nonEmptyUrl = url => url.startsWith('~') ? { finUrl: url.substring(1), newTab: true } : {
  finUrl: url,
  newTab: false
}
const getUrlData = (url) => url ? nonEmptyUrl(url) : emptyUrl(url)

Here is the solution for it:这是它的解决方案:

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

You can do it with a single conditional operator (and you can use ?. to make it slightly shorter.)您可以使用单个条件运算符来执行此操作(您可以使用?.使其稍微短一些。)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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