From: Lady Date: Thu, 8 Sep 2022 02:13:16 +0000 (-0700) Subject: Make toIntN & toUintN more accommodating X-Git-Tag: 0.1.4~1 X-Git-Url: https://git.ladys.computer/Pisces/commitdiff_plain/10f5f13665b3454942bc8b1c49c6d4c46a5ac560?ds=sidebyside;hp=c1364974d7add579702210b7dfe8396ea20c0ccf Make toIntN & toUintN more accommodating These used to not handle non‐integers well, and now do gracefully. --- diff --git a/numeric.js b/numeric.js index 44c7cd5..1d0a543 100644 --- a/numeric.js +++ b/numeric.js @@ -605,15 +605,37 @@ export const { return { toIntN: (n, $) => { const prim = toPrimitive($); - const big·int = toBigInt(prim); - const intN = asIntN(n, big·int); - return typeof prim === "bigint" ? intN : toNumber(intN); + if (typeof prim === "bigint") { + // The primitive value is a big·int. + return asIntN(n, prim); + } else { + // The primitive value is not a big·int. + const int = trunc(prim); + if (!isFiniteNumber(int) || int == 0) { + // The truncated value is zero or not finite. + return 0; + } else { + // The truncated value is finite. + return toNumber(asIntN(n, toBigInt(int))); + } + } }, toUintN: (n, $) => { const prim = toPrimitive($); - const big·int = toBigInt(prim); - const uintN = asUintN(n, big·int); - return typeof prim === "bigint" ? uintN : toNumber(uintN); + if (typeof prim === "bigint") { + // The primitive value is a big·int. + return asUintN(n, prim); + } else { + // The primitive value is not a big·int. + const int = trunc(prim); + if (!isFiniteNumber(int) || int == 0) { + // The truncated value is zero or not finite. + return 0; + } else { + // The truncated value is finite. + return toNumber(asUintN(n, toBigInt(int))); + } + } }, }; })(); diff --git a/numeric.test.js b/numeric.test.js index ea99bc9..96f51c1 100644 --- a/numeric.test.js +++ b/numeric.test.js @@ -150,6 +150,11 @@ describe("toIntN", () => { it("[[Call]] works with numbers", () => { assertStrictEquals(toIntN(2, 7), -1); }); + + it("[[Call]] works with non‐integers", () => { + assertStrictEquals(toIntN(2, 7.21), -1); + assertStrictEquals(toIntN(2, Infinity), 0); + }); }); describe("toIntegerOrInfinity", () => { @@ -212,4 +217,9 @@ describe("toUintN", () => { it("[[Call]] works with numbers", () => { assertStrictEquals(toUintN(2, 7), 3); }); + + it("[[Call]] works with non‐integers", () => { + assertStrictEquals(toUintN(2, 7.21), 3); + assertStrictEquals(toUintN(2, Infinity), 0); + }); });