What are some alternatives to write cleaner, better, and smarter if/else function?
I am actually trying to convert my code to something more readable.
const statusComment = () => {
const isApproved = "🟢";
const unApproved = "🔴";
let status;
// is approved and has comment.
if (checkApproval && comment) {
status = `${isApproved} — ${comment}`;
// is not approved and has comment.
} else if (!checkApproval && comment) {
status = `${unApproved} — ${comment}`;
// has comment.
} else if (comment) {
status = comment;
// is approved.
} else if (checkApproval) {
status = isApproved;
} else {
// is not approved.
status = unApproved;
}
return status;
};
Let's break it down a bit: your string has two parts that are joined by a dash -
:
checkApproval
boolean value.comment
.Also, do note that your third statement is not possible to get to, since comment
is always truthy in the first two statements and it's combined with a boolean flag.
Therefore, you can create an array with the compulsory first part with this ternary statement:
const status = [checkApproval ? "🟢" : "🔴"];
For the second optional part, you push into it when comment
is truthy:
if (comment) status.push(comment);
Here's your modified code:
const statusComment = () => {
const status = [checkApproval ? "🟢" : "🔴"];
if (comment) status.push(comment);
return status.join(' — ');
};
Let's make a table based on your existing code:
checkApproval comment out
true true green - comment
false true red - comment
true comment duplicate/unnecessary?
true green
false red
So we see that if there is true for checkApproval, it's green, and red otherwise.
Let's make that right now:
const status = `${checkApproval ? "🟢" : "🔴"}`;
And if there's a comment, there is a dash followed by the comment. This we can represent too:
const status = `${checkApproval ? "🟢" : "🔴"}${comment ? " - " + comment : ""}`;
If there is no comment, nothing is added after.
Then we can just return status
normally.