I have a function that takes in an object that consists of 4 arrays, the first array has a list of customers that have a file-A missing, the second has a list of customers that need to update a file-A, the third has a list of customers that have file-B missing, and the fourth has a list of customers that need to update file-B.
I have function that takes in the objects and checks all the 4 arrays and then generates an email like this "This is an email to inform you that customers A and B are missing file-A, customers C and D need to update file-A, customers A and B are missing file-B and customers F and E need to update file-B"
The way I was thinking of generating this email message is through an if statement but the things is there are 16 different conditions I would have to customise a message for.
I feel like writing 15 else statements isn't the way to go.
I drew out all the possible combinations below, 0 being there are no customers in the array and 1 being there is a customer in the array.
I guess my question is does anyone know of a more efficient way of doing this? And in general how do you deal with complicated if statements that could have 16 different conditions?
Generating the email in your question only needs one if, but not where you think. Your email will look like this:
function generateMessage(data) {
// Assuming data looks like this:
// type Data = {
// aMissing: string[];
// aUpdate: string[];
// bMissing: string[];
// bUpdate: string[];
// };
function joinListWithAnd(list) {
if (list && list.length > 1) {
const last = list.pop();
return `${list.join(", ")} and ${last}`;
}
return list && list.length ? list[0] : null
}
const pieces = {
aMissing: " are missing file-A",
aUpdate: " need to update file-A",
bMissing: " are missing file-B",
bUpdate: " need to update file-B",
};
const statusMessages = [];
for (const [key, value] of Object.entries(data)) {
statusMessages.push(`customers ${joinListWithAnd(data.value)} ${pieces[key]}`);
}
return `This is an email to inform you that ${joinListWithAnd(statusMessages)}.`
}
console.log(generateMessage({aMissing: ["A", "B"], bMissing: ["C"], bUpdate: ["A", "B", "C"]}))
The structure of the email you want to send is the same as the structure of the data you want to send, so no conditional checks need to be run to build the bulk structure. The only conditional part is figuring out how to format a list, as the English language specifies that the word and appears second to last in a list with length greater than 1.