From fc2f27eea8e63d5ef418f12c452de633a63fff04 Mon Sep 17 00:00:00 2001 From: Gabriel Arazas Date: Sat, 2 Mar 2024 12:58:48 +0800 Subject: [PATCH] bahaghari/lib: add `clamp` --- subprojects/bahaghari/lib/default.nix | 2 +- subprojects/bahaghari/lib/trivial.nix | 17 ++++++++++++++++- .../bahaghari/tests/lib/trivial/default.nix | 15 +++++++++++++++ 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/subprojects/bahaghari/lib/default.nix b/subprojects/bahaghari/lib/default.nix index 24e589a7..9dfbed58 100644 --- a/subprojects/bahaghari/lib/default.nix +++ b/subprojects/bahaghari/lib/default.nix @@ -22,7 +22,7 @@ pkgs.lib.makeExtensible tinted-theming = callLibs ./tinted-theming.nix; inherit (self.trivial) importYAML toYAML toBaseDigitsWithGlyphs - generateGlyphSet generateConversionTable generateBaseDigitType; + generateGlyphSet generateConversionTable generateBaseDigitType clamp; inherit (self.hex) isHexString; inherit (self.math) abs pow percentage; diff --git a/subprojects/bahaghari/lib/trivial.nix b/subprojects/bahaghari/lib/trivial.nix index fc2c67de..6cf9d91d 100644 --- a/subprojects/bahaghari/lib/trivial.nix +++ b/subprojects/bahaghari/lib/trivial.nix @@ -138,8 +138,23 @@ rec { chars = pkgs.lib.stringToCharacters digit; maxDigits = (pkgs.lib.length chars) - 1; convertDigitToDec = - pkgs.lib.lists.imap0 (i: v: conversionTable.${v} * (pow base (maxDigits - i))) chars; + pkgs.lib.lists.imap0 (i: v: conversionTable.${v} * (lib.math.pow base (maxDigits - i))) chars; in pkgs.lib.foldl (sum: v: sum + v) 0 convertDigitToDec; }; + + /* Given a range of two numbers, ensure the value is only returned within the + range. + + Type: clamp :: Number -> Number -> Number -> Number + + Example: + clamp 0 255 654 + => 255 + + clamp (-100) 100 (-234) + => -100 + */ + clamp = min: max: value: + pkgs.lib.min max (pkgs.lib.max min value); } diff --git a/subprojects/bahaghari/tests/lib/trivial/default.nix b/subprojects/bahaghari/tests/lib/trivial/default.nix index 97b37d2f..d55861c6 100644 --- a/subprojects/bahaghari/tests/lib/trivial/default.nix +++ b/subprojects/bahaghari/tests/lib/trivial/default.nix @@ -210,4 +210,19 @@ pkgs.lib.runTests { expr = lib.trivial.toYAML { } { hello = "there"; }; expected = "{\"hello\":\"there\"}"; }; + + testNumberClamp = { + expr = lib.trivial.clamp 1 10 4; + expected = 4; + }; + + testNumberClampMin = { + expr = lib.trivial.clamp 1 10 (-5); + expected = 1; + }; + + testNumberClampMax = { + expr = lib.trivial.clamp 1 10 453; + expected = 10; + }; }