From 1db66cd480110b97ff6c94c28751de5e031fe524 Mon Sep 17 00:00:00 2001 From: Isabelle Viktoria Maciohsek Date: Wed, 7 Oct 2020 23:52:57 +0300 Subject: [PATCH] Add copySign --- snippets/copySign.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 snippets/copySign.md diff --git a/snippets/copySign.md b/snippets/copySign.md new file mode 100644 index 000000000..7a968f4b9 --- /dev/null +++ b/snippets/copySign.md @@ -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 +```