Files
30-seconds-of-code/snippets/copySign.md
Isabelle Viktoria Maciohsek 27c168ce55 Bake date into snippets
2021-06-13 13:55:00 +03:00

486 B

title, tags, firstSeen, lastUpdated
title tags firstSeen lastUpdated
copySign math,beginner 2020-10-07T23:52:57+03:00 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