diff --git a/subprojects/bahaghari/lib/trivial.nix b/subprojects/bahaghari/lib/trivial.nix index f70f3eee..bbaa1818 100644 --- a/subprojects/bahaghari/lib/trivial.nix +++ b/subprojects/bahaghari/lib/trivial.nix @@ -195,4 +195,22 @@ rec { */ scale = { inMin, inMax, outMin, outMax }: v: ((v - inMin) * (outMax - outMin)) / ((inMax - inMin) + outMin); + + /* Returns a null value if the condition fails. Otherwise, returns the given + value `as`. + + Type: optionalNull :: Bool -> Any -> Any + + Example: + optionalNull true "HELLO" + => "HELLO" + + optionalNull (null != null) "HELLO" + => null + */ + optionalNull = cond: as: + if cond then + as + else + null; } diff --git a/subprojects/bahaghari/tests/lib/trivial/default.nix b/subprojects/bahaghari/tests/lib/trivial/default.nix index fd318e1d..278a8ab5 100644 --- a/subprojects/bahaghari/tests/lib/trivial/default.nix +++ b/subprojects/bahaghari/tests/lib/trivial/default.nix @@ -260,4 +260,14 @@ lib.runTests { expr = self.trivial.isNumber true; expected = false; }; + + testOptionalNull = { + expr = self.trivial.optionalNull true "HELLO"; + expected = "HELLO"; + }; + + testOptionalNull2 = { + expr = self.trivial.optionalNull false "HELLO"; + expected = null; + }; }