Last active
October 21, 2017 19:49
-
-
Save Beraliv/f3509dd52cb49c9c3615b5b84264196c to your computer and use it in GitHub Desktop.
Find the max of 2 numbers without any condition: if-else-clause, ternary operator, third-party library or core implementation.
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
/** | |
* The only difference here is that sign(0) = 1 | |
*/ | |
let sign = a => { | |
let signBit = a >>> 31; | |
return signBit * -1 + (1 - signBit) * 1; | |
}; | |
let abs = a => a * sign(a); | |
/** | |
* (min + max + max - min) / 2 = 2 * max / 2 = max | |
*/ | |
let max = (a, b) => (a + b + abs(a - b)) / 2; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment