bahaghari/lib: add math.mod

Now, it's the real modulo operation.
This commit is contained in:
Gabriel Arazas 2024-06-15 19:46:34 +08:00
parent 61720afeb2
commit ff0ddb0e27
No known key found for this signature in database
GPG Key ID: 62104B43D00AA360
2 changed files with 47 additions and 0 deletions

View File

@ -252,6 +252,23 @@ rec {
in in
floor (difference + 0.5) * nearest; 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 /* Similar to the nixpkgs' `trivial.mod` but retain the decimal values. This
is just an approximation from ECMAScript's implementation of the remainder is just an approximation from ECMAScript's implementation of the remainder
operator. operator.

View File

@ -227,6 +227,36 @@ lib.runTests {
expected = 1.4142135624; 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 = { testMathRemainder = {
expr = self.math.remainder 65.5 3; expr = self.math.remainder 65.5 3;
expected = 2.5; expected = 2.5;