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.