Skip to content

Instantly share code, notes, and snippets.

@petrosalema
Created July 14, 2011 23:58
Show Gist options
  • Save petrosalema/1083756 to your computer and use it in GitHub Desktop.
Save petrosalema/1083756 to your computer and use it in GitHub Desktop.
JavaScript Max Challenge
/**
* 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