]> Lady’s Gitweb - Pisces/commitdiff
Add toIntegerOrInfinity to numeric.js
authorLady <redacted>
Sun, 4 Sep 2022 21:15:36 +0000 (14:15 -0700)
committerLady <redacted>
Fri, 12 May 2023 03:56:47 +0000 (20:56 -0700)
numeric.js
numeric.test.js

index 78ea64c50aa080746ac4a206e41e71b2c5ebb017..44c7cd5649772257f688cf5572236ce2452295e7 100644 (file)
@@ -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.
  *
index e82e04b88d6fc7b49086174143e9233d7254c391..ea99bc97910346aa1ff67e96b57e8d66cadee5a7 100644 (file)
@@ -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);
This page took 0.068605 seconds and 4 git commands to generate.