-
-
Save andreystarkov/09df90bdb6529f167641eb776ccbccc4 to your computer and use it in GitHub Desktop.
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
const expr = 'Papayas'; | |
// old way | |
switch (expr) { | |
case 'Oranges': | |
console.log('Oranges are $0.59 a pound.'); | |
break; | |
case 'Apples': | |
console.log('Apples are $0.32 a pound.'); | |
break; | |
case 'Bananas': | |
console.log('Bananas are $0.48 a pound.'); | |
break; | |
case 'Cherries': | |
console.log('Cherries are $3.00 a pound.'); | |
break; | |
case 'Mangoes': | |
console.log('Mangoes and papayas are $2.79 a pound.'); | |
break; | |
case 'Papayas': | |
console.log('papayas are $2.79 a pound.'); | |
break; | |
default: | |
console.log('Sorry, we are out of ' + expr + '.'); | |
} | |
// create a function to handle the switch statement | |
const match = (expression, cases) => { | |
return cases[expression] || cases?.default; | |
}; | |
// new way | |
const matched = match(expr, { | |
Oranges: 'Oranges are $0.59 a pound.', | |
Mangoes: 'Mangoes and papayas are $2.79 a pound.', | |
Papayas: 'Mangoes and papayas are $2.79 a pound.', | |
default: `Sorry, we are out of ${expr}.`, | |
}); | |
console.log(matched); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment