bahaghari/lib: add pow and generateConversionTable

This commit is contained in:
Gabriel Arazas 2024-02-28 10:43:37 +08:00
parent 74b7879e51
commit 103988226b
No known key found for this signature in database
GPG Key ID: ADE0C41DAB221FCC
3 changed files with 67 additions and 2 deletions

View File

@ -21,6 +21,6 @@ pkgs.lib.makeExtensible
tinted-theming = callLibs ./tinted-theming.nix;
inherit (self.trivial) importYAML toYAML toBaseDigitsWithGlyphs
generateGlyphSet;
inherit (self.hex) toHexString isHexString;
generateGlyphSet generateConversionTable pow;
inherit (self.hex) toHexString isHexString hexToDec;
})

View File

@ -73,4 +73,50 @@
glyphsList;
in
pkgs.lib.foldl (acc: glyph: acc // glyph) { } glyphsList';
/* Generates a conversion table for a sorted list of glyphs to its decimal
number. Suitable for creating your own conversion function. Accepts the
same argument as `generateGlyphSet`.
Type: generateConversionTable :: [ String ] -> Attrs
Example:
generateGlyphSet [ "0" "1" "2" "3" "4" "5" "6" "7" "8 "9" "A" "B" "C" "D" "E" "F" ]
=> {
"0" = 0;
"1" = 1;
# ...
"E" = 14;
"F" = 15;
}
*/
generateConversionTable = glyphsList:
let
glyphsList' =
pkgs.lib.lists.imap0
(i: glyph: pkgs.lib.nameValuePair glyph i)
glyphsList;
in
pkgs.lib.listToAttrs glyphsList';
/* Exponentiates the given base with the exponent.
Type: pow :: Int -> Int -> Int
Example:
pow 2 3
=> 8
pow 6 4
=> 1296
*/
pow = base: exponent:
# I'll just make this linearly recursive instead.
let
iter = product: counter: max-count:
if counter > max-count
then product
else (iter (product * base) (counter + 1) max-count);
in
iter 1 1 exponent;
}

View File

@ -77,6 +77,20 @@ pkgs.lib.runTests {
expected = customBase24Glyphs;
};
testGenerateConversionTable = {
expr = lib.trivial.generateConversionTable [ "A" "B" "C" "D" "E" "F" "G" "H" ];
expected = {
"A" = 0;
"B" = 1;
"C" = 2;
"D" = 3;
"E" = 4;
"F" = 5;
"G" = 6;
"H" = 7;
};
};
testBaseDigitWithCustomOctalGlyph = {
expr = lib.trivial.toBaseDigitsWithGlyphs 8 9 customOctalGlyphs;
expected = "BB";
@ -143,4 +157,9 @@ pkgs.lib.runTests {
expr = lib.trivial.toYAML { } { hello = "there"; };
expected = "{\"hello\":\"there\"}";
};
testPow = {
expr = lib.trivial.pow 2 8;
expected = 256;
};
}