Saw this in a PR at work:
let result = '';
if (bar && foo) {
result = 'bingo bango bongo';
} else if (!bar && foo) {
result = 'bish bash bosh';
} else if (bar) {
result = 'ez peazy lemon squeezy';
}
return result
Or something similar, made me think of how you could write this cleaner.
if (fooCondition) {
return barCondition ? 'bingo bango bongo' : 'bish bash bosh';
} else {
return barCondition ? 'ez peazy lemon squeezy' : '';
}
Seeing as we are not doing anything else aside from returning, we can use all turneries.
return fooCondition
? barCondition
? 'bingo bango bongo'
: 'bish bash bosh'
: barCondition
? 'ez peazy lemon squeezy'
: '';
Often we can place these into an object if we want to get results based on a few parameters.
return ({
true: {
true: 'bingo bango bongo',
false: 'bish bash bosh',
},
false: {
true: 'ez peazy lemon squeezy',
false: '',
},
})[fooCondition][barCondition];
We can code golf this up a bit.
return ({
1: {
1: 'bingo bango bongo',
0: 'bish bash bosh',
},
0: {
1: 'ez peazy lemon squeezy',
0: '',
},
})[+fooCondition][+barCondition];
An object with numbers for keys is just an array.
return [['bingo bango bongo', 'bish bash bosh'], ['ez peazy lemon squeezy', '']][
+fooCondition
][+barCondition];
Much better.