gpt-3.5-turbo-0301· OpenAI WildChat-4.8M (AI2)
how can i avoid adding ternary statements like this const icon = type === "SUCCESS" ?…
- User
how can i avoid adding ternary statements like this const icon = type === "SUCCESS" ? successIcon : warningIcon; const alt = type === "SUCCESS" ? "Success icon" : "Warning icon";
- Assistant
There are a few ways to avoid ternary statements like this:
- Use switch statements instead:
let icon, alt; switch (type) { case "SUCCESS": icon = successIcon; alt = "Success icon"; break; case "WARNING": icon = warningIcon; alt = "Warning icon"; break; default: icon = defaultIcon; alt = "Default icon"; }- Use an object to map values:
const iconMap = { SUCCESS: { icon: successIcon, alt: "Success icon" }, WARNING: { icon: warningIcon, alt: "Warning icon" }, DEFAULT: { icon: defaultIcon, alt: "Default icon" } }; const {icon, alt} = iconMap[type] || iconMap.DEFAULT;- Use a function to handle the logic:
function getIconAndAlt(type) { if (type === "SUCCESS") { return {icon: successIcon, alt: "Success icon"}; } else if (type === "WARNING") { return {icon: warningIcon, alt: "Warning icon"}; } else { return {icon: defaultIcon, alt: "Default icon"}; } } const {icon, alt} = getIconAndAlt(type);