From ff0ddb0e271cf390570a9e4b4f6bad270a0e25c9 Mon Sep 17 00:00:00 2001 From: Gabriel Arazas Date: Sat, 15 Jun 2024 19:46:34 +0800 Subject: [PATCH] bahaghari/lib: add math.mod Now, it's the real modulo operation. --- subprojects/bahaghari/lib/math.nix | 17 ++++++++++++++ subprojects/bahaghari/tests/lib/math.nix | 30 ++++++++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/subprojects/bahaghari/lib/math.nix b/subprojects/bahaghari/lib/math.nix index 30e9ed3c..3d1e8a34 100644 --- a/subprojects/bahaghari/lib/math.nix +++ b/subprojects/bahaghari/lib/math.nix @@ -252,6 +252,23 @@ rec { in floor (difference + 0.5) * nearest; + /* Given a base and a modulus, returns the value of a modulo operation. + + Type: mod :: Number -> Number -> Number + + Example: + mod 5 4 + => 1 + + mod 1245 4.5 + => 3 + + mod 19 (-12) + => -5 + */ + mod = base: modulus: + remainder ((remainder base modulus) + modulus) modulus; + /* Similar to the nixpkgs' `trivial.mod` but retain the decimal values. This is just an approximation from ECMAScript's implementation of the remainder operator. diff --git a/subprojects/bahaghari/tests/lib/math.nix b/subprojects/bahaghari/tests/lib/math.nix index eb413c81..6743a7aa 100644 --- a/subprojects/bahaghari/tests/lib/math.nix +++ b/subprojects/bahaghari/tests/lib/math.nix @@ -227,6 +227,36 @@ lib.runTests { expected = 1.4142135624; }; + testMathMod = { + expr = self.math.mod 5 4; + expected = 1; + }; + + testMathMod2 = { + expr = self.math.mod 1245 4.5; + expected = 3; + }; + + testMathModPositiveOperands = { + expr = self.math.mod 19 12; + expected = 7; + }; + + testMathModNegativeDividend = { + expr = self.math.mod (-19) 12; + expected = 5; + }; + + testMathModNegativeDivisor = { + expr = self.math.mod 19 (-12); + expected = -5; + }; + + testMathModNegativeOperands = { + expr = self.math.mod (-19) (-12); + expected = -7; + }; + testMathRemainder = { expr = self.math.remainder 65.5 3; expected = 2.5;