Skip to content

Latest commit

 

History

History
23 lines (19 loc) · 508 Bytes

copySign.md

File metadata and controls

23 lines (19 loc) · 508 Bytes
title tags expertise firstSeen lastUpdated
Copy sign to number
math
beginner
2020-10-07 23:52:57 +0300
2020-10-07 23:52:57 +0300

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