r/shittyprogramming • u/Skymt1 • Jun 11 '23
Write a function that negates an integer! [JS]
function neg(i) {
let f = n=>!n?n:n<0?-f(-n):n%3?n+1:-n+2;
return f(f(f(i)));
}
Usage:
var aVariableToNegate = 5;
aVariableToNegate = neg(aVariableToNegate);
console.log('The variable is now ' + aVariableToNegate ); // -5
29
Upvotes
8
u/[deleted] Jun 11 '23
Very interesting. Would be great to see some performance benchmarks.
3
u/diMario Jun 11 '23
Does this work with floating point too? And what about dates, or more generally, strings?
4
u/Aphix Jun 11 '23
Also JS:
const flip = (x) => ~(x-1)flip(5) === -5 // true2
u/PandaAromatic8901 Jun 11 '23
9007199254740991