isOccupied and vacant are two keys that are destructured out of a document
const { isOccupied, vacant } = doc || {};
boolDetermination = (isOccupied, vacant) => {
if (isOccupied && isOccupied === vacant) { < --- if isOccupied exists and is equal to vacant return the value of isOccupied
return isOccupied
}
if (isOccupied && !vacant) { <--- if isOccupied exists and vacant doesnt, set vacant to opposite of isOccupied
return !isOccupied
}
if (!isOccupied && vacant) { if isOccupied doesnt exist and vacant does set vacant to initial bool value
return vacant
}
}
$set: { vacant: boolDetermination(isOccupied, vacant) <--- where I set the value of the vacant field
Is there a better faster way of doing this?
Also I'm not entirely sure if my code covers all cases such as only one of the two fields existing in the initial object structure.
I am currently writing a migration and the following conditions will determine whether the vacant field is true or not.
if isOccupied = true set vacant to false
if vacant = true set vacant as true
if isOccupied = true and vacant = true, set vacant as true
if isOccupied = false, set vacant as true
if isOccupied = false and vacant = false, set vacant as false
I want to optimize my function and was wondering how it could be made better so I don't have to use 3 (or more) if/conditional statements
Thank you and any help is appreciated!
CodePudding user response:
Just a boolean algebra. Or Table of truth. Or Karnaugh Map. Choose whatever is better for you. The only issue is im not correctly sure about the expected inputs-outputs of your logic for this function but you can change that easilly.
Example 1: Table of truth
const boolDetermination = (isOccupied, vacant) => {
// https://mathworld.wolfram.com/TruthTable.html
// param1, param2, result
const truthTable = [
[false, false, false],
[false, true, true],
[true, false, false],
[true, true, true]
];
const set = truthTable.find((x) => x[0] === isOccupied && x[1] === vacant);
return set[2];
};
If i got your logic right - then you can notice that the result of table of truth is exactly equal to the vacant
variable you have.
const boolDetermination2 = (isOccupied, vacant) => {
return vacant;
};
Outputs are pretty the same but again. If you have a different table of truth - comment me and i'll update the answer.
Now about Karnaugh Map. They are used in combinatorial logic minimization. You can use any online-solver you like. You just need to set the values you want in the Truth Map. https://charlie-coleman.com/experiments/kmap/
Tell me if you have any additional questions or issues