Skip to content

Instantly share code, notes, and snippets.

@Beraliv
Last active October 21, 2017 19:49
Show Gist options
  • Save Beraliv/f3509dd52cb49c9c3615b5b84264196c to your computer and use it in GitHub Desktop.
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.
/**
* 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