From 9d122c32c0f034d844e3c755db1042ab71c16159 Mon Sep 17 00:00:00 2001 From: Gabriel Arazas Date: Sat, 2 Mar 2024 17:18:15 +0800 Subject: [PATCH] bahaghari/lib: update `percentage` Also reordered the arguments to make it more "functional". --- subprojects/bahaghari/lib/math.nix | 16 +++++++++++---- subprojects/bahaghari/tests/lib/math.nix | 26 +++++++++++++++++++++--- 2 files changed, 35 insertions(+), 7 deletions(-) diff --git a/subprojects/bahaghari/lib/math.nix b/subprojects/bahaghari/lib/math.nix index 883b40fd..c8e71c51 100644 --- a/subprojects/bahaghari/lib/math.nix +++ b/subprojects/bahaghari/lib/math.nix @@ -93,14 +93,22 @@ rec { Type: percentage :: Number -> Number -> Number Example: - percentage 4 100.0 + percentage 100.0 4 => 4 - percentage 5 200.0 + percentage 200.0 5 => 10 + + percentage 55.4 58 + => 32.132 + + percentage 0 24654 + => 0 */ - percentage = number: value: - number / (100.0 / value); + percentage = value: number: + if value == 0 + then 0 + else number / (100.0 / value); /* Given a number, round up (or down) its number to the nearest integer. diff --git a/subprojects/bahaghari/tests/lib/math.nix b/subprojects/bahaghari/tests/lib/math.nix index b9145882..097c536c 100644 --- a/subprojects/bahaghari/tests/lib/math.nix +++ b/subprojects/bahaghari/tests/lib/math.nix @@ -12,7 +12,7 @@ pkgs.lib.runTests { }; testMathPowZero = { - expr = lib.math.pow 34 0; + expr = lib.math.pow 31 0; expected = 1; }; @@ -27,15 +27,35 @@ pkgs.lib.runTests { }; testMathPercentage = { - expr = lib.math.percentage 100 50; + expr = lib.math.percentage 50 100; expected = 50; }; testMathPercentage2 = { - expr = lib.math.percentage 453 13; + expr = lib.math.percentage 13 453; expected = 58.89; }; + testMathPercentageNegative = { + expr = lib.math.percentage (-20) 500; + expected = -100; + }; + + testMathPercentageNegative2 = { + expr = lib.math.percentage (-64) 843; + expected = -539.52; + }; + + testMathPercentageZero = { + expr = lib.math.percentage 0 45723; + expected = 0; + }; + + testMathPercentageZero2 = { + expr = lib.math.percentage 0 (-3423); + expected = 0; + }; + testMathGrow = { expr = lib.math.grow 500 12; expected = 72;