]> Lady’s Gitweb - Pisces/commitdiff
Add toIntegralNumber to numeric.js 0.2.0
authorLady <redacted>
Mon, 19 Sep 2022 02:31:02 +0000 (19:31 -0700)
committerLady <redacted>
Fri, 12 May 2023 03:56:48 +0000 (20:56 -0700)
Also allow big·int arguments in toIntegerOrInfinity.

numeric.js
numeric.test.js

index ce92585a4a887b7c66f2af33a5cc344615ddf422..64d9a80502f5fc8b363d59acb5aa18d9e5e988d7 100644 (file)
@@ -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.
  *
index 6c58d04d7971187b2ca04d5fbabfb97aa29bb92b..dfb806301bbf7a3587cce3bc98b308664787b055 100644 (file)
@@ -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);
   });
 });
 
This page took 0.047985 seconds and 4 git commands to generate.