简化不可读的嵌套if / else

时间:2019-03-22 14:06:46

标签: javascript ecmascript-6 nested

我需要基于每个子对象的2个变量来确定其父对象的状态。我想出了一个可行的解决方案,但这包括一个嵌套的“ if-else if-else”。不用说,它看起来不是很优雅。

我想知道是否有一种方法可以简化这一过程。我已经弄混了一些map / reduce代码,但是没有找到比下面的代码更优雅的东西。

const parent = {
  children: [{
      connected: true,
      online: true

    },
    {
      connected: true,
      online: true
    }
  ]
}


// all online & all connected  => connected
// all online & some connected => partially disconnected
// all online & none connected => disconnected
// some online => partially offline
// none online => offline

const onlineArr = parent.children.map(c => c.online);
const connectedArr = parent.children.map(c => c.connected);
let status;

if (!onlineArr.includes(true)) {
  status = 'Offline';
} else if (!onlineArr.includes(false)) {
  if (!connectedArr.includes(true)) {
    status = 'Disconnected';
  } else if (!connectedArr.includes(false)) {
    status = 'Connected';
  } else {
    status = 'Partially disconnected';
  }
} else {
  status = 'Partially offline';
}

console.log(status);

1 个答案:

答案 0 :(得分:0)

我只是将全部/部分/没有检查提取到一个函数中:

  const overAll = (array, key, value, /*results in */ all, some, none) =>
    array.every(it => it[key] === value) ? all : (array.some(it => it[key] === value) ? some : none);

然后就这么简单:

 const status = (
   overAll(parent.children, "online", true, undefined, "Partially offline", "Offline") ||
   overAll(parent.children, "connected", true, "Connected", "Partially connected", "not connected")
);

但是您的if / else已经很干净了IMO:)