]> Lady’s Gitweb - Pisces/commitdiff
Add maybe to `function.js`
authorLady <redacted>
Sun, 3 Dec 2023 17:57:41 +0000 (12:57 -0500)
committerLady <redacted>
Sun, 3 Dec 2023 17:57:41 +0000 (12:57 -0500)
function.js
function.test.js

index 71e4d098d41dfbad04e954dfd42c06d552af1a38..5d59af1a6c56f99beb4a1fad81db62ada3b7394c 100644 (file)
@@ -421,6 +421,13 @@ export const isConstructor = ($) =>
     construct(function () {}, [], $)
   );
 
+/**
+ * Calls the provided callback with the provided argument if the
+ * provided argument is not nullish; otherwise, returns the provided
+ * argument unmodified.
+ */
+export const maybe = ($, callback) => $ == null ? $ : callback($);
+
 /**
  * Returns whether the provided object inherits from the prototype of
  * the provided function.
index 0a58a367af38433412a700d230bb5995d1da13ae..09b9f7e00160eb998a82f6714dbaece118aec180 100644 (file)
 import {
   assert,
   assertEquals,
+  assertSpyCall,
+  assertSpyCalls,
   assertStrictEquals,
   assertThrows,
   describe,
   it,
+  spy,
 } from "./dev-deps.js";
 import {
   bind,
@@ -27,6 +30,7 @@ import {
   identity,
   isCallable,
   isConstructor,
+  maybe,
   ordinaryHasInstance,
 } from "./function.js";
 
@@ -991,6 +995,42 @@ describe("isConstructor", () => {
   });
 });
 
+describe("maybe", () => {
+  it("[[Call]] calls if not nullish", () => {
+    const wrapper = spy(() => "success");
+    assertStrictEquals(maybe(0, wrapper), "success");
+    assertSpyCalls(wrapper, 1);
+    assertSpyCall(wrapper, 0, {
+      args: [0],
+      self: undefined,
+      returned: "success",
+    });
+  });
+
+  it("[[Call]] does not call if nullish", () => {
+    const wrapper = spy(() => "success");
+    assertStrictEquals(maybe(null, wrapper), null);
+    assertStrictEquals(maybe(undefined, wrapper), undefined);
+    assertSpyCalls(wrapper, 0);
+  });
+
+  it("[[Construct]] throws an error", () => {
+    assertThrows(() => new maybe(true, ($) => $));
+  });
+
+  describe(".length", () => {
+    it("[[Get]] returns the correct length", () => {
+      assertStrictEquals(maybe.length, 2);
+    });
+  });
+
+  describe(".name", () => {
+    it("[[Get]] returns the correct name", () => {
+      assertStrictEquals(maybe.name, "maybe");
+    });
+  });
+});
+
 describe("ordinaryHasInstance", () => {
   it("[[Call]] walks the prototype chain", () => {
     const constructor = class {
This page took 0.102548 seconds and 4 git commands to generate.