Last active
October 23, 2024 19:58
-
-
Save trvswgnr/f05a140dfbf4b6b59b0ed7628ab3f7ed to your computer and use it in GitHub Desktop.
real modulo operation in typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Real modulo operation that works correctly with negative numbers. | |
* | |
* JavaScript's `%` operator returns the remainder of a division operation, | |
* which may be negative. This function corrects that by adding the base before | |
* taking the remainder. | |
*/ | |
export function mod(dividend: number, modulus: number): number { | |
return ((dividend % modulus) + modulus) % modulus; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment