]> Lady’s Gitweb - Pisces/commitdiff
Make toIntN & toUintN more accommodating
authorLady <redacted>
Thu, 8 Sep 2022 02:13:16 +0000 (19:13 -0700)
committerLady <redacted>
Fri, 12 May 2023 03:56:47 +0000 (20:56 -0700)
These used to not handle non‐integers well, and now do gracefully.

numeric.js
numeric.test.js

index 44c7cd5649772257f688cf5572236ce2452295e7..1d0a5435bb75512cd18b657759fdc6fccff85c89 100644 (file)
@@ -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)));
+        }
+      }
     },
   };
 })();
index ea99bc97910346aa1ff67e96b57e8d66cadee5a7..96f51c1614e8cde3d1f7302d7e860ec1b278376d 100644 (file)
@@ -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);
+  });
 });
This page took 0.066439 seconds and 4 git commands to generate.