From: Lady Date: Sun, 3 Dec 2023 17:57:41 +0000 (-0500) Subject: Add maybe to `function.js` X-Git-Url: https://git.ladys.computer/Pisces/commitdiff_plain/4ab95bf467c40e8c6e81f309bd9a0d33518fbee4?ds=inline Add maybe to `function.js` --- diff --git a/function.js b/function.js index 71e4d09..5d59af1 100644 --- a/function.js +++ b/function.js @@ -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. diff --git a/function.test.js b/function.test.js index 0a58a36..09b9f7e 100644 --- a/function.test.js +++ b/function.test.js @@ -10,10 +10,13 @@ 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 {