【问题标题】:How can I avoid nested ternary expressions in my code?如何避免在我的代码中嵌套三元表达式?
【发布时间】:2018-02-26 13:40:03
【问题描述】:

我有这样的代码。如何使用 JavaScript 中的函数式编程以更简洁、更优雅的方式编写它?我想摆脱嵌套的三元表达式。有什么想法吗?

props => ({
            iconColor: props.isPriority ? (props.isCompleted ? variables.color.lightpurple : variables.color.purple ) : variables.color.gray3,
            iconName: props.isPriority ? 'star-full' : 'star-empty',
          }))

这是该代码的其余部分:

编辑:

const enhance: React$HOC<*, InitialProps> = compose(
      withProps(props => ({
        iconColor: props.isPriority ? (props.isCompleted ? variables.color.lightpurple : variables.color.purple) : variables.color.gray3,
        iconName: props.isPriority ? 'star-full' : 'star-empty',
      }))
    )

【问题讨论】:

  • 创建一个函数,调用它
  • 清洁剂??已经很干净了
  • 清洁度是非常主观的。
  • @Jonasw,是的,但我的 linter 不高兴:44:16 error Do not nest ternary expressions [no-nested-ternary]
  • @JaromandaX - 我可以创建该函数并在 withProps 包装器中调用它吗?它会起作用吗?

标签: javascript functional-programming purely-functional


【解决方案1】:

我同意@JaromandaX 关于使用函数的观点。这让你的 JSX 保持干净并且你的逻辑可以重用。

除此之外,为避免嵌套三元运算符,您可以尝试以下操作:

  • 保留所有可能值的数组/映射
  • 根据标志,创建二进制字符串并将其转换为数字。
  • 返回提供的索引处的值

function withTernary(a, b){
  return a ? (b ? 'test': 'foo') : 'bar';
}

function withoutTernary(a, b){
  var result = ['bar', undefined, 'foo', 'test'];
  // or may be a map
  /*
  * map = {
  *    '00': 'bar',
  *    '10': 'foo',
  *    '11': 'test'
  * }
  */
  var index = parseInt((+a) + '' + (+b), 2);
  return result[index];
}

var testCase = [[0,0], [1, 0], [1,1]];

testCase.forEach(x => {
  console.log('With Ternary:', withTernary(...x));
  console.log('Without Ternary:', withoutTernary(...x));
})

【讨论】:

  • 注意: 这是避免嵌套三元运算符的另一种方法。如果您认为此答案中的任何内容不必要/不需要/不当,请在投票时发表评论。祝你有美好的一天。
【解决方案2】:

可以使用 IIaFE(立即调用的箭头函数表达式):

props => ({
        iconColor:(_=>{
           if(props.isPriority){
             if(props.isCompleted){
               return variables.color.lightpurple;
             }
             return variables.color.purple;
           }
           return variables.color.gray3;
        })(),
        iconName:(_=>{ 
           if(props.isPriority){
              return 'star-full';
           }
           return 'star-empty';
       })()
}))

【讨论】:

  • 我不认为,我们需要箭头函数,因为我们没有在其中使用this。此外,拥有一个预定义函数总是比拥有一个内联函数更好,因为它增加了重用它的可能性。
  • IIFE 并不是特别实用。而是使用像const apply = (...args) =&gt; f =&gt; f(...args) 这样的可重用函数。代码变得更容易理解,您甚至可以在 f 的参数中解构:apply(props) (({isPriority, isCompleted}) =&gt; { switch (isPriority) {...}})。
【解决方案3】:

是的,但我的 linter 不开心:44:16 error Do not nest ternary expressions [no-nested-ternary]

如果这是您唯一的问题,那么解决方案很简单。创建自己的条件函数:

const iff = (condition, then, otherwise) => condition ? then : otherwise;

props => ({
  iconColor: props.isPriority ?
    iff(props.isCompleted, variables.color.lightpurple, variables.color.purple) :
    variables.color.gray3,
  iconName: props.isPriority ? 'star-full' : 'star-empty',
})

现在你的 linter 不应该抱怨了。话虽如此,您应该在 linter 中禁用 [no-nested-ternary]。你的 linter 认为嵌套条件不好,这有点愚蠢。

【讨论】:

  • 这只是在欺骗 ESLint 并添加间接性。我同意如果没有合适的替代方案,则应禁用此规则。您能否编辑答案以包含更重要的更改 eslint 配置的解决方案,而不是添加对代码库没有任何好处并且只会使其更难阅读的功能?
  • 这不是“有点愚蠢”,linter 不是在抱怨嵌套条件,而是因为嵌套三元运算符通常不利于代码清晰。
  • @Eric Van Der Dijs 这值得商榷。来自函数式编程背景,我认为嵌套条件对于代码清晰来说是可以的,直到它变得过于笨拙。应该由程序员团队来决定什么是好代码,什么是坏代码。 linter 不应将其首选样式强加给程序员。
  • 请注意,我从未说过“嵌套条件不利于清晰”。我只谈到了使用三元运算符编写嵌套条件(即:条件?'foo':anotherConditon?'bar':'baz'),但当然,代码风格完全取决于你的团队决策,我只是在谈论一个共同的标准。
【解决方案4】:

在这种情况下,您可以考虑反转条件以删除三元组的“不自然”嵌套。仍然会有嵌套,但它可以写成扁平的——不带括号——这意味着你可以将它整齐地排列在多行中:

props => ({
    iconColor:
        !props.isPriority ? variables.color.gray3
        : props.isCompleted ? variables.color.lightpurple
        : variables.color.purple,
    iconName: props.isPriority ? 'star-full' : 'star-empty',
})

这样做的缺点是使用了负面条件,我通常会尽量避免,因为它们比正面条件更难遵循。

另一种选择是使用&amp;&amp; 展平条件:

props => ({
    iconColor:
        props.isPriority && props.isCompleted ? variables.color.lightpurple
        : props.isPriority ? variables.color.purple
        : variables.color.gray3,
    iconName: props.isPriority ? 'star-full' : 'star-empty',
})

【讨论】:

    猜你喜欢
    • 2016-11-19
    • 2020-03-04
    • 2020-02-01
    • 2020-10-23
    • 2016-05-16
    • 2011-06-21
    • 2017-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多