Last active
October 11, 2024 07:32
-
-
Save Kcko/73abdf119d395ec49394551295d350b5 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
// https://blog.stackademic.com/how-to-optimize-complex-conditionals-in-javascript-0fcaf0add82a | |
const onButtonClick = (status) => { | |
if (status == 1) { | |
jumpTo('Index Page'); | |
} else if (status == 2 || status == 3) { | |
jumpTo('Failure Page'); | |
} else if (status == 4) { | |
jumpTo('Success Page'); | |
} else if (status == 5) { | |
jumpTo('Cancel Page'); | |
} else { | |
jumpTo('Other Actions'); | |
} | |
}; | |
// 1 | |
// if => switch | |
const onButtonClick = (status) => { | |
switch (status) { | |
case 1: | |
jumpTo('Index Page'); | |
break; | |
case 2: | |
case 3: | |
jumpTo('Failure Page'); | |
break; | |
case 4: | |
jumpTo('Success Page'); | |
break; | |
case 5: | |
jumpTo('Cancel Page'); | |
break; | |
default: | |
jumpTo('Other Actions'); | |
} | |
}; | |
// ------------------------------------------ | |
const onButtonClick = (status, identity) => { | |
if (identity == 'guest') { | |
if (status == 1) { | |
// logic for guest status 1 | |
} else if (status == 2) { | |
// logic for guest status 2 | |
} | |
// Additional logic for other statuses... | |
} else if (identity == 'master') { | |
if (status == 1) { | |
// logic for master status 1 | |
} | |
// Additional logic for other statuses... | |
} | |
}; | |
// 2 | |
// interesting solution ;) | |
// nested if to map with keys where key mean concaten ifs.. | |
const actions = new Map([ | |
['guest_1', () => { /* logic for guest status 1 */ }], | |
['guest_2', () => { /* logic for guest status 2 */ }], | |
['master_1', () => { /* logic for master status 1 */ }], | |
['master_2', () => { /* logic for master status 2 */ }], | |
['default', () => { /* default logic */ }], | |
]); | |
const onButtonClick = (identity, status) => { | |
const action = actions.get(`${identity}_${status}`) || actions.get('default'); | |
action(); | |
}; | |
// 3 | |
// object with keys instead of use of ifs | |
const actions = { | |
'1': 'Index Page', | |
'2': 'Failure Page', | |
'3': 'Failure Page', | |
'4': 'Success Page', | |
'5': 'Cancel Page', | |
'default': 'Other Actions', | |
}; | |
const onButtonClick = (status) => { | |
const action = actions[status] || actions['default']; | |
jumpTo(action); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment