Files
30-seconds-of-code/js/snippets/copy-sign.md
2023-05-03 20:39:23 +03:00

488 B

title, type, tags, cover, dateModified
title type tags cover dateModified
Copy sign to number snippet
math
keyboard-tea 2020-10-07T23:52:57+03:00

Returns the absolute value of the first number, but the sign of the second.

  • Use Math.sign() to check if the two numbers have the same sign.
  • Return x if they do, -x otherwise.
const copySign = (x, y) => Math.sign(x) === Math.sign(y) ? x : -x;
copySign(2, 3); // 2
copySign(2, -3); // -2
copySign(-2, 3); // 2
copySign(-2, -3); // -2