Created
July 14, 2011 23:58
-
-
Save petrosalema/1083756 to your computer and use it in GitHub Desktop.
JavaScript Max Challenge
This file contains hidden or 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
/** | |
* JavaScript Max Challenge: | |
* A function that returns the greater of 2 numbers | |
* without using math.min, math.max, >, <, ==, != | |
* | |
* ie: | |
* given a > b | |
* assert max(a, b) == a | |
* | |
* Solution: | |
* if a > b then a - b < 0 | |
* if n < 0 then n + Math.abs(n) == 0 | |
* JavaScript coerces 0 to false | |
* | |
* ie: | |
* (a > b) && ((n = a - b) < 0) | |
* (n < 0) && (n + Math.abs(n) == 0) | |
* (0 == false) == true | |
* | |
* Tests: | |
* max(8, 9) // 9 | |
* max(8, -9) // 8 | |
*/ | |
function max (a, b) { | |
var n = a - b; | |
var d = n + Math.abs(n); | |
return d ? a : b; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment