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
翻译自:https://www.30secondsofcode.org/js/s/copy-sign-to-number