【问题标题】:Optimal expression to evaluate condition and set both flag and value评估条件并设置标志和值的最佳表达式
【发布时间】:2021-08-17 01:39:12
【问题描述】:

下面是两个函数,它们遍历对象集合以评估是否有任何项目对象的 id 等于函数的 id 参数。如果为 true,那么它会设置一个活动标志并将当前变量设置为等于 id。

注意事项:

  1. 函数 longVersion(id) 如果是详细/更长的方法
  2. function shortVersion(id) 是我目前的最佳方法

问题

  1. 在 ES6 和/或 lodash 中是否有更好的方法来实现相同的结果?

const items = {1:{id:1,active:false},2:{id:2,active:false}, 3:{id:3,active:false}}
let current = 0;

function longerVersion(id) {
  for (const k in this.items) {
    if (this.items[k].id === id) {
      this.items[k].active = true
      current = id
    } else {
      this.items[k].active = false
    }
  }
}

function shorterVersion(id) {
  for (const k in this.items) {
    items[k].active = items[k].id === id && ((current = id) && true)
  }
}

longerVersion(2);
console.log(current); // expected outcome : (current === 2)
console.log(items); // expected outcome :  items: {1:{id:1,active:false},2:{id:2,active:true}, 3:{id:3,active:false}}

shorterVersion(3);
console.log(current); // expected outcome : (current === 3)
console.log(items); // expected outcome :  items: {1:{id:1,active:false},2:{id:2,active:false}, 3:{id:3,active:true}}

【问题讨论】:

  • 将项目切换为数组感觉如何?然后你可以使用 Array.find 和其他有用的函数来代替 for 循环。
  • “更好”怎么样? “最优”在什么意义上?就个人而言,我讨厌将作业与布尔表达式混合在一起,但这就是我的看法,伙计。
  • @HereticMonkey 我同意,但是你最终会得到代码繁重的详细选项
  • @James 顺便说一句,我对数组很好,如果你有解决方案
  • 这就是我们有缩小器的原因,所以我们不必担心这样的废话。

标签: javascript ecmascript-6 lodash


【解决方案1】:

假设集合确实是一个普通对象,并且您不需要对象原型链中的属性,in 关键字越来越不受欢迎,而支持更新的Object.keys 等。这是一种使用它的方法,一个箭头函数和可选链接,是额外的 Ecma-ish:

function ecmaVersion(id) {
    const key = Object.keys(items).find((key) =>
        items[key].active = (items[key].id === id))
    return current = items[key]?.id
}

lodash 等效项将涉及_.findKey

【讨论】:

【解决方案2】:

在函数范围内更新current 是您要避免的副作用。而是让它成为函数的返回值。

const items = {1:{id:1,active:false},2:{id:2,active:false}, 3:{id:3,active:false}};

const functionalVersion = (items, id) => Object.values(items).reduce((acc, x) => {
  x.active = x.id === id;
  return x.active ? id : acc;
}, -1);

let current = functionalVersion(items, 2);
console.log(current); // expected outcome : (current === 2)
console.log(items); // expected outcome :  items: {1:{id:1,active:false},2:{id:2,active:true}, 3:{id:3,active:false}}

current = functionalVersion(items, 3);
console.log(current); // expected outcome : (current === 3)
console.log(items); // expected outcome :  items: {1:{id:1,active:false},2:{id:2,active:false}, 3:{id:3,active:true}}

items id 都没有与该id 匹配时,该函数返回-1

我不喜欢表达式中的赋值,但如果这是你的事,你可以用单线来做:

const functionalVersion = (items, id) => Object.values(items).reduce((acc, x) => x.active = x.id === id ? id : acc, -1);

【讨论】:

  • 效果很好!杰出的!允许我将其提取到可以注入任何组件的实用程序函数中。谢谢一百万!
猜你喜欢
  • 2010-11-29
  • 1970-01-01
  • 2019-03-16
  • 2015-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多