From: Lady Date: Mon, 19 Sep 2022 02:31:02 +0000 (-0700) Subject: Add toIntegralNumber to numeric.js X-Git-Tag: 0.2.0^0 X-Git-Url: https://git.ladys.computer/Pisces/commitdiff_plain/5b8f999fb29590d65fb09cf89c46ad986ef7c377?ds=sidebyside;hp=f3e417be2077db5839dcada4aa1395ae2e9337ba Add toIntegralNumber to numeric.js Also allow big·int arguments in toIntegerOrInfinity. --- diff --git a/numeric.js b/numeric.js index ce92585..64d9a80 100644 --- a/numeric.js +++ b/numeric.js @@ -650,10 +650,10 @@ export const { * Returns the result of converting the provided number to an integer * or infinity. * - * ☡ This function does not allow big·int arguments. + * ※ This function will never return negative zero. */ export const toIntegerOrInfinity = ($) => { - const integer = trunc($); + const integer = trunc(toNumber($)); if (isNan(integer) || integer == 0) { // The provided value truncs to nan or (positive or negative) zero. return 0; @@ -669,6 +669,17 @@ export const toIntegerOrInfinity = ($) => { } }; +/** + * Returns the result of converting the provided number to an integral + * number. + * + * ※ This function will never return negative zero. + */ +export const toIntegralNumber = ($) => { + const n = toIntegerOrInfinity($); + return !isFiniteNumber(n) || n == 0 ? 0 : n; +}; + /** * Returns the result of converting the provided value to a number. * diff --git a/numeric.test.js b/numeric.test.js index 6c58d04..dfb8063 100644 --- a/numeric.test.js +++ b/numeric.test.js @@ -25,6 +25,7 @@ import { toBigInt, toFloat32, toIntegerOrInfinity, + toIntegralNumber, toIntN, toNumber, toNumeric, @@ -189,7 +190,37 @@ describe("toIntegerOrInfinity", () => { }); it("[[Call]] returns negative infinity for negative infinity", () => { - assertStrictEquals(toIntegerOrInfinity(Infinity), Infinity); + assertStrictEquals(toIntegerOrInfinity(-Infinity), -Infinity); + }); + + it("[[Call]] works with big·ints", () => { + assertStrictEquals(toIntegerOrInfinity(2n), 2); + }); +}); + +describe("toIntegralNumber", () => { + it("[[Call]] converts nan to zero", () => { + assertStrictEquals(toIntegralNumber(NaN), 0); + }); + + it("[[Call]] converts negative zero to positive zero", () => { + assertStrictEquals(toIntegralNumber(-0), 0); + }); + + it("[[Call]] drops the fractional part of negative numbers", () => { + assertStrictEquals(toIntegralNumber(-1.79), -1); + }); + + it("[[Call]] returns zero for infinity", () => { + assertStrictEquals(toIntegralNumber(Infinity), 0); + }); + + it("[[Call]] returns zero for negative infinity", () => { + assertStrictEquals(toIntegralNumber(-Infinity), 0); + }); + + it("[[Call]] works with big·ints", () => { + assertStrictEquals(toIntegralNumber(2n), 2); }); });