Skip to content

Instantly share code, notes, and snippets.

@andreystarkov
Forked from Yusfuu/new-switch-cases.js
Created April 25, 2022 11:29
Show Gist options
  • Save andreystarkov/09df90bdb6529f167641eb776ccbccc4 to your computer and use it in GitHub Desktop.
Save andreystarkov/09df90bdb6529f167641eb776ccbccc4 to your computer and use it in GitHub Desktop.
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