The issue with legacy conditional statements.
The main issue is, it is ugly and boring. See the Part 1.
It takes a lot of time to write conditions and maintain them consider the below.
private demo(myVar: string): string {
if(myVar === 'condition') {
return myVar.substring(1,3);
}
if(myVar === 'demo') {
return myVar.substring(1,2);
}
if(myVar === 'thing') {
return myVar.substring(1,4);
}
if(myVar === 'demo1') {
return myVar.substring(1,5);
}
if(myVar === 'demo5') {
return myVar.substring(1,2);
}
return '';
}
Now the above code can be good in some case but we can do better.
USING OBJECT FOR CONDITIONING
private demo1(myVar: string): string {
const myObject: { [key: string]: string; } = {
'condition': myVar.substring(1,3),
'demo': myVar.substring(1,2),
'thing': myVar.substring(1,4),
'demo1': myVar.substring(1,5),
'demo5': myVar.substring(1,2),
}
return myObject[myVar];
}
demo1('condition');
It will work same as the above if
statements but it is a clean code.
Want to check the default condition as well?
private demo1(myVar: string): string {
const myObject: { [key: string]: string; } = {
'condition': myVar.substring(1,3),
'demo': myVar.substring(1,2),
'thing': myVar.substring(1,4),
'demo1': myVar.substring(1,5),
'demo5': myVar.substring(1,2),
default: '',
}
if(!myObject[myVar]) return myObject['default'];
return myObject[myVar];
}
This reduces the overall cognitive complexity as well.
With this we can even have function calls.
public coc(troopName: string, quantity: number): string {
const bookForCOC: { [key: string]: any } = {
'barbarian': () => quantity > 30 ? 'Use it behind kind' : 'Use it to destroy',
'archer': () => quantity > 20 ? 'Use it behind queen' : 'Use it to destroy',
'balloon': () => quantity > 20 ? 'Use it behind dragons' : 'Use it after air defense is destroyed',
'dragon': () => quantity > 3 ? 'Use it at a single place' : 'Use it anywhere else',
default: () => 'Use some good troops to win'
}
if(!bookForCOC[troopName]) return bookForCOC['default']();
return bookForCOC[troopName]();
}
This can be used as an alternative for conditional statements
If you like the post follow me for more
Top comments (0)