From 3825c8568cbd6b5c2c0686554203680c4415f9b6 Mon Sep 17 00:00:00 2001 From: Gabriel Arazas Date: Tue, 4 Jun 2024 19:45:29 +0800 Subject: [PATCH] bahaghari/lib: add `trivial.optionalNull` --- subprojects/bahaghari/lib/trivial.nix | 18 ++++++++++++++++++ .../bahaghari/tests/lib/trivial/default.nix | 10 ++++++++++ 2 files changed, 28 insertions(+) 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; + }; }