From 0b7b3ffd7d0036cce712fc0a939213d931d62bce Mon Sep 17 00:00:00 2001 From: Gabriel Arazas Date: Sat, 2 Mar 2024 12:54:59 +0800 Subject: [PATCH] bahaghari/lib: add `grow'` and `isWithinRange` Also updated the order of the arguments to make it more usable in functional programming paradigm or whatever. --- subprojects/bahaghari/lib/math.nix | 37 +++++++++++++++++------- subprojects/bahaghari/tests/lib/math.nix | 24 +++++++++++++-- 2 files changed, 49 insertions(+), 12 deletions(-) diff --git a/subprojects/bahaghari/lib/math.nix b/subprojects/bahaghari/lib/math.nix index a0fd6d84..883b40fd 100644 --- a/subprojects/bahaghari/lib/math.nix +++ b/subprojects/bahaghari/lib/math.nix @@ -41,6 +41,20 @@ rec { in if exponent < 0 then (1 / value) else value; + /* Returns a boolean whether the given number is within the given (inclusive) range. + + Type: isWithinRange :: Number -> Number -> Number -> Bool + + Example: + isWithinRange 30 50 6 + => false + + isWithinRange 0 100 75 + => true + */ + isWithinRange = min: max: number: + (pkgs.lib.max number min) <= (pkgs.lib.min number max); + /* Given a number, make it grow by given amount of percentage. A value of 100 should make the number doubled. @@ -53,23 +67,26 @@ rec { grow 55.5 100 => 111 */ - grow = number: value: + grow = value: number: number + (percentage number value); - /* Given a number, make it smaller by given amount of percentage. - A value of 100 should zero the number. + /* Similar to `grow` but only limits to be within the given (inclusive) + range. - Type: shrink :: Number -> Number -> Number + Type: grow' :: Number -> Number -> Number -> Number Example: - shrink 4 50.0 - => 2 + grow' 0 255 12 100 + => 24 - shrink 55.5 100 - => 0 + grow' 1 10 5 (-200) + => 1 */ - shrink = number: value: - number - (percentage number value); + grow' = min: max: value: number: + let + res = grow number value; + in + pkgs.lib.min max (pkgs.lib.max res min); /* Given a number, return its value by the given percentage. diff --git a/subprojects/bahaghari/tests/lib/math.nix b/subprojects/bahaghari/tests/lib/math.nix index f8e137c4..b9145882 100644 --- a/subprojects/bahaghari/tests/lib/math.nix +++ b/subprojects/bahaghari/tests/lib/math.nix @@ -37,15 +37,25 @@ pkgs.lib.runTests { }; testMathGrow = { - expr = lib.math.grow 12 500; + expr = lib.math.grow 500 12; expected = 72; }; testMathGrow2 = { - expr = lib.math.grow 5.5 55.5; + expr = lib.math.grow 55.5 5.5; expected = 8.5525; }; + testMathGrowVariantMax = { + expr = lib.math.grow' 0 255 130 100; + expected = 255; + }; + + testMathGrowVariantMin = { + expr = lib.math.grow' 0 255 130 (-500); + expected = 0; + }; + testMathRoundDown = { expr = lib.math.round 2.3; expected = 2; @@ -55,4 +65,14 @@ pkgs.lib.runTests { expr = lib.math.round 2.8; expected = 3; }; + + testMathWithinRange = { + expr = lib.math.isWithinRange (-100) 100 50; + expected = true; + }; + + testMathWithinRange2 = { + expr = lib.math.isWithinRange 5 10 (-5); + expected = false; + }; }