bahaghari/lib: add isNumber and scale

This commit is contained in:
Gabriel Arazas 2024-05-21 20:27:12 +08:00
parent 3e3dbcfbbe
commit f882c30209
No known key found for this signature in database
GPG Key ID: 62104B43D00AA360
3 changed files with 72 additions and 1 deletions

View File

@ -38,7 +38,8 @@ pkgs.lib.makeExtensible
tinted-theming = callLibs ./tinted-theming.nix; tinted-theming = callLibs ./tinted-theming.nix;
inherit (self.trivial) importYAML toYAML toBaseDigitsWithGlyphs inherit (self.trivial) importYAML toYAML toBaseDigitsWithGlyphs
generateGlyphSet generateConversionTable generateBaseDigitType clamp; generateGlyphSet generateConversionTable generateBaseDigitType clamp
isNumber scale;
inherit (self.hex) isHexString; inherit (self.hex) isHexString;
inherit (self.math) abs pow percentage; inherit (self.math) abs pow percentage;

View File

@ -160,4 +160,39 @@ rec {
*/ */
clamp = min: max: value: clamp = min: max: value:
lib.min max (lib.max min value); lib.min max (lib.max min value);
/* Given a value, check if it's a number type.
Type: isNumber :: Number -> bool
Example:
isNumber 3.0
=> true
isNumber 653
=> true
isNumber true
=> false
*/
isNumber = v:
lib.isInt v || lib.isFloat v;
/* Given an initial range of integers, scale the given number with its own
set of range.
Type: scale :: Attrs -> Number -> Number
Example:
scale { inMin = 0; inMax = 15; outMin = 0; outMax = 255; } 4
=> 68
scale { inMin = 0; inMax = 15; outMin = 0; outMax = 255; } (-4)
=> -68
scale { inMin = 0; inMax = 15; outMin = 0; outMax = 255; } 15
=> 255
*/
scale = { inMin, inMax, outMin, outMax }: v:
((v - inMin) * (outMax - outMin)) / ((inMax - inMin) + outMin);
} }

View File

@ -225,4 +225,39 @@ lib.runTests {
expr = self.trivial.clamp 1 10 453; expr = self.trivial.clamp 1 10 453;
expected = 10; expected = 10;
}; };
testNumberScale = {
expr = self.trivial.scale { inMin = 0; inMax = 15; outMin = 0; outMax = 255; } 15;
expected = 255;
};
testNumberScale2 = {
expr = self.trivial.scale { inMin = 0; inMax = 15; outMin = 0; outMax = 255; } 4;
expected = 68;
};
testNumberScale3 = {
expr = self.trivial.scale { inMin = 0; inMax = 15; outMin = 0; outMax = 255; } (-4);
expected = (-68);
};
testIsNumber1 = {
expr = self.trivial.isNumber 3;
expected = true;
};
testIsNumber2 = {
expr = self.trivial.isNumber 4.09;
expected = true;
};
testIsNumber3 = {
expr = self.trivial.isNumber "HELLO";
expected = false;
};
testIsNumber4 = {
expr = self.trivial.isNumber true;
expected = false;
};
} }