javascript - 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.
解决方案
首先,让我们通过反转 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 };
推荐阅读
- regex - 重定向 [R=301] 在 .htaccess 中结束下一次迭代?
- javascript - 如何将我的数据库中的发送数据添加到 html 中的文本区域表单
- python - 如何为 Scipy/Numpy 安装 64 位 lapack
- python - 如何将这些词添加到我的视频帧中?
- github - 来自html文件的Github html预览不起作用
- python - 应用 random.sample() 大整数输入时如何修改代码以避免溢出错误?
- javascript - 内容类型在 Chrome 版本 84 中设置为 text/plain 在线浏览器与 firefox 中的应用程序/javascript
- python - 解析 XML 在 python 中创建格式不正确的错误
- scala - 将函数内的 Int 更新为全局
- r - str_detect 多列使用cross