I need to determine the status of a parent object based on 2 variables of each of its children. I came up with a working solution, but this includes a nested "if-else if-else". Needless to say, it doesn't look very elegant.
I was wondering if there is a way to simplify this. I have muddled around with some map/reduce code, but did not get to anything that is more elegant than the code below.
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);
Run code snippetExpand snippet
JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)