Skip to content

Instantly share code, notes, and snippets.

@trvswgnr
Last active October 23, 2024 19:58
Show Gist options
  • Save trvswgnr/f05a140dfbf4b6b59b0ed7628ab3f7ed to your computer and use it in GitHub Desktop.
Save trvswgnr/f05a140dfbf4b6b59b0ed7628ab3f7ed to your computer and use it in GitHub Desktop.
real modulo operation in typescript
/**
* 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