Add copySign

This commit is contained in:
Isabelle Viktoria Maciohsek
2020-10-07 23:52:57 +03:00
parent 5169b41c1b
commit 1db66cd480

20
snippets/copySign.md Normal file
View File

@ -0,0 +1,20 @@
---
title: copySign
tags: math,beginner
---
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.
```js
const copySign = (x, y) => Math.sign(x) === Math.sign(y) ? x : -x;
```
```js
copySign(2, 3); // 2
copySign(2, -3); // -2
copySign(-2, 3); // 2
copySign(-2, -3); // -2
```