Created
February 9, 2024 11:01
-
-
Save esedic/c11361d990e0f65b2f1fc214a90deab8 to your computer and use it in GitHub Desktop.
Javascirpt if/else vs switch vs object mapping
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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