Skip to content

Instantly share code, notes, and snippets.

@esedic
Created February 9, 2024 11:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save esedic/c11361d990e0f65b2f1fc214a90deab8 to your computer and use it in GitHub Desktop.
Save esedic/c11361d990e0f65b2f1fc214a90deab8 to your computer and use it in GitHub Desktop.
Javascirpt if/else vs switch vs object mapping
// Scenario, wher we need to determine a discount based on a customer's loyalty level
// 1. Traditional if-else approach:
function calculateDiscount(loyaltyLevel) {
console.time('if else time');
if (loyaltyLevel === 'GOLD') {
applyGoldDiscount();
} else if (loyaltyLevel === 'SILVER') {
applySilverDiscount();
} else if (loyaltyLevel === 'BRONZE') {
applyBronzeDiscount();
}
console.timeEnd('if else time');
}
// 2. Alternative: a switch statement
function calculateDiscount(loyaltyLevel) {
console.time('switch time');
switch (loyaltyLevel) {
case 'GOLD':
applyGoldDiscount();
break;
case 'SILVER':
applySilverDiscount();
break;
case 'BRONZE':
applyBronzeDiscount();
break;
}
console.timeEnd('switch time');
}
// 3. The simplicity of object mapping
function calculateDiscount(loyaltyLevel) {
console.time('object time');
const discountMap = {
'GOLD': applyGoldDiscount,
'SILVER': applySilverDiscount,
'BRONZE': applyBronzeDiscount
};
discountMap[loyaltyLevel] && discountMap[loyaltyLevel]();
console.timeEnd('object time');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment