bahaghari/lib: add clamp

This commit is contained in:
Gabriel Arazas 2024-03-02 12:58:48 +08:00
parent 0b7b3ffd7d
commit fc2f27eea8
No known key found for this signature in database
GPG Key ID: ADE0C41DAB221FCC
3 changed files with 32 additions and 2 deletions

View File

@ -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;

View File

@ -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);
}

View File

@ -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;
};
}