]> Lady’s Gitweb - Pisces/commitdiff
Add completesNormally to function.js
authorLady <redacted>
Sat, 22 Jul 2023 07:39:17 +0000 (00:39 -0700)
committerLady <redacted>
Mon, 4 Sep 2023 19:40:24 +0000 (15:40 -0400)
This is a convenience function which returns true if calling the
argument results in a normal completion (i·e not a throw), and false
otherwise.

function.js
function.test.js

index 5f397a92d2708331cddc63bef2b82d0cdc72eb68..ca7cad52503f98db03d6d5e5e91ad152723588d3 100644 (file)
@@ -95,6 +95,32 @@ export const {
   construct,
 } = Reflect;
 
+/**
+ * Returns whether calling the provided function with no `this` value
+ * or arguments completes normally; that is, does not throw an error.
+ *
+ * ☡ This function will throw an error if the provided argument is not
+ * callable.
+ */
+export const completesNormally = ($) => {
+  if (!isCallable($)) {
+    // The provided value is not callable; this is an error.
+    throw new TypeError(
+      `Piscēs: Cannot determine completion of noncallable value: ${$}`,
+    );
+  } else {
+    // The provided value is callable.
+    try {
+      // Attempt to call the function and return true if this succeeds.
+      $();
+      return true;
+    } catch {
+      // Calling the function did not succeed; return false.
+      return false;
+    }
+  }
+};
+
 /**
  * Returns the provided value.
  *
index 17e77e24c58ae657a9c2bf025fd87a55def0043f..a9a5f3f3b07b51b8f5778ce5575591ff7a48e440 100644 (file)
 import {
   assertEquals,
   assertStrictEquals,
+  assertThrows,
   describe,
   it,
 } from "./dev-deps.js";
 import {
   bind,
   call,
+  completesNormally,
   construct,
   identity,
   isCallable,
@@ -115,6 +117,33 @@ describe("call", () => {
   });
 });
 
+describe("completesNormally", () => {
+  it("[[Call]] returns true for functions which complete normally", () => {
+    assertStrictEquals(completesNormally(() => {}), true);
+  });
+
+  it("[[Call]] returns false for functions which throw", () => {
+    assertStrictEquals(
+      completesNormally(() => {
+        throw null;
+      }),
+      false,
+    );
+  });
+
+  it("[[Call]] throws when the argument is not callable", () => {
+    assertThrows(() => {
+      completesNormally(null);
+    });
+  });
+
+  it("[[Call]] throws when the argument is not provided", () => {
+    assertThrows(() => {
+      completesNormally();
+    });
+  });
+});
+
 describe("construct", () => {
   it("[[Call]] defaults to the constructor as the target", () => {
     const constructor = class {};
This page took 0.026055 seconds and 4 git commands to generate.