@mtf I’ve finally got round to looking at your function challenge
This function always returns the higher/maximum of 2 numbers…
…EXCEPT when A is 0 (falsy), B is a truthy number, and A is greater than B (i.e. B is negative)
Was I meant to discover this flaw in this function?
Here is my attempt at an explanation of why it always maximises, except in this one situation:
Situation 1
When both A and B are truthy numbers, and A is greater than B
e.g. when A is 10 and B is 5
10 > 5 => true && 10 => truthy || 5 => truthy
true && 10 // returns the second truthy => 10
10 || 5 // returns the first truthy => 10
Result: the function returns 10 (the higher number)
Situation 2
When both A and B are truthy numbers, and A is less than B
e.g. when A is 5 and B is 10
5 > 10 => false && 5 => truthy || 10 => truthy
false && 5 => false
false || 10 => 10
Result: the function returns 10 (the higher number)
Situation 3
When A is a truthy number, B is 0 (falsy), and A is greater than B
e.g. when A is 10 and B is 0
10 > 0 => true && 10 => truthy || 0 => falsy
true && 10 => returns the second truthy => 10
10 || 0 => 10
Result: the function returns 10 (the higher number)
Situation 4
When A is a truthy number, B is 0 (falsy), and A is less than B
e.g. when A is -10 and B is 0
-10 > 0 => false && -10 => truthy || 0 => falsy
false && -10 => false
false || 0 => 0
Result: the function returns 0 (the higher number)
Situation 5 - THE EXCEPTION
When A is 0 (falsy), B is a truthy number, and A is greater than B
e.g. when A is 0 and B is -10
0 > -10 => true && 0 => falsy || -10 => truthy
true && 0 => 0
0 || -10 => -10
Result: the function returns -10 (the LOWER number)
Situation 6
When A is a 0 (falsy), B is a truthy number, and A is less than B
e.g. when A is 0 and B is 10
0 > 10 => false && 0 => falsy || 10 => truthy
false && 0 => false
false || 10 => 10
Result: the function returns 10 (the higher number)
Situation 7
When both A and B are 0 (falsy)
0 > 0 => false && 0 => falsy || 0 => falsy
false && 0 => false
false || 0 => 0
Result: the function returns 0 (the only number, and therefore the maximum)
Situation 8
When A and B are the same truthy number.
e.g. when A and B are both 10
10 > 10 => false && 10 => truthy || 10 => truthy
false && 10 => false
false || 10 => 10
Result: the function returns 10 (the only number, and therefore the maximum)
Situation 9
When A and B are the same truthy number, and this number is negative.
e.g. when A and B are both -10
-10 > -10 => false && -10 => truthy || -10 => truthy
false && -10 => false
false || -10 => -10
Result: the function returns -10 (the only number, and therefore the maximum)
So, I guess we need to add an if( )
statement to the function for it to work with any pair of numbers, as follows:
const maximize = (a, b) => {
if (!(a === 0 && a > b)) {
return a > b && a || b
} else {
return a
}
}
Any thoughts?