From: Lady Date: Sun, 4 Sep 2022 21:15:36 +0000 (-0700) Subject: Add toIntegerOrInfinity to numeric.js X-Git-Tag: 0.1.3~2 X-Git-Url: https://git.ladys.computer/Pisces/commitdiff_plain/8fcb8f6d937fadd7aa8016f8ba33004d1bd79bf0?hp=2edbddced262b90f8422e77fe8ec61a9f8c82e68 Add toIntegerOrInfinity to numeric.js --- diff --git a/numeric.js b/numeric.js index 78ea64c..44c7cd5 100644 --- a/numeric.js +++ b/numeric.js @@ -618,6 +618,29 @@ export const { }; })(); +/** + * Returns the result of converting the provided number to an integer + * or infinity. + * + * ☡ This function does not allow big·int arguments. + */ +export const toIntegerOrInfinity = ($) => { + const integer = trunc($); + if (isNan(integer) || integer == 0) { + // The provided value truncs to nan or (positive or negative) zero. + return 0; + } else if (integer == POSITIVE_INFINITY) { + // The provided value truncs to positive infinity. + return POSITIVE_INFINITY; + } else if (integer == NEGATIVE_INFINITY) { + // The provided value truncs to negative infinity. + return NEGATIVE_INFINITY; + } else { + // The provided value truncs to an integer. + return integer; + } +}; + /** * Returns the result of converting the provided value to a number. * diff --git a/numeric.test.js b/numeric.test.js index e82e04b..ea99bc9 100644 --- a/numeric.test.js +++ b/numeric.test.js @@ -22,6 +22,7 @@ import { sgn, toBigInt, toFloat32, + toIntegerOrInfinity, toIntN, toNumber, toNumeric, @@ -151,6 +152,28 @@ describe("toIntN", () => { }); }); +describe("toIntegerOrInfinity", () => { + it("[[Call]] converts nan to zero", () => { + assertStrictEquals(toIntegerOrInfinity(NaN), 0); + }); + + it("[[Call]] converts negative zero to positive zero", () => { + assertStrictEquals(toIntegerOrInfinity(-0), 0); + }); + + it("[[Call]] drops the fractional part of negative numbers", () => { + assertStrictEquals(toIntegerOrInfinity(-1.79), -1); + }); + + it("[[Call]] returns infinity for infinity", () => { + assertStrictEquals(toIntegerOrInfinity(Infinity), Infinity); + }); + + it("[[Call]] returns negative infinity for negative infinity", () => { + assertStrictEquals(toIntegerOrInfinity(Infinity), Infinity); + }); +}); + describe("toNumber", () => { it("[[Call]] converts to a number", () => { assertStrictEquals(toNumber(2n), 2);