I have the following JS code were i am displaying different status based on the response key from API. is there any better approach to optimise this code so that i don’t have to check each case with IF, in case if the number of status increases
if (data.shippingStatus) {
let shippingStatus = data.shippingStatus.toString();
if (shippingStatus === "AWAITING_SHIPMENT") {
shippingStatus = "Awaiting Shipment";
} else if (shippingStatus === "SHIPPED") {
shippingStatus = "Shipped";
} else if (shippingStatus === "DELIVERED") {
shippingStatus = "Delivered";
} else if (shippingStatus === "CANCELLED") {
shippingStatus = "Cancelled";
}
resData.push(setData(data.shippingStatus ? shippingStatus : ""));
}
CodePudding user response:
Try object mapper:
const statusMapper: {[key:string]: string} = {
AWAITING_SHIPMENT: "Awaiting Shipment",
SHIPPED: "Shipped",
DELIVERED: "Delivered",
CANCELLED: "Cancelled"
};
if (data.shippingStatus) {
let shippingStatus = data.shippingStatus.toString();
resData.push(setData(data.shippingStatus ? statusMapper[shippingStatus] : ""));
}
EDIT: Added type to the mapper
CodePudding user response:
There are different approaches to your question. If you're just looking for a solid solution for the current problem aka mapping values, you can either create an object mapper as the other answers suggest or just a simple function that formats your string e.g.:
var text = "AWAITING_SHIPMENT";
text = text.toLowerCase()
.split('_')
.map((s) => s.charAt(0).toUpperCase() s.substring(1))
.join(' ');
console.log(text);
But if you're looking into the subject in a broader sense, you can use dynamic dispatch via polymorphism. This is an example that uses polymorphism to change behavior based on a type.
CodePudding user response:
How my implementation works, it splits the status by _ and capitalize it, and finally return a new status, as required
// Dummy Data
const data = {
shippingStatus:"AWAITING_SHIPMENT"
}
// New Proposal
if(data.shippingStatus){
const { shippingStatus } = data;
const status =
shippingStatus.split('_')
.map(string => string.charAt(0).toUpperCase() string.slice(1).toLowerCase())
.join(" ");
console.log(status)
// no need to check for data.shippingStatus twice
// while you're still within if condition, just do the following :
// resData.push(setDate(status))
}
CodePudding user response:
Have map of possible statuses
let statuses = {
'AWAITING_SHIPMENT': 'Awaiting Shipment',
'SHIPPED': 'Shipped',
...
};
resData.push(setData(data.shippingStatus ? statuses[shippingStatus] : ""));