Skip to content

Instantly share code, notes, and snippets.

@Quaese
Created February 7, 2025 15:58
Show Gist options
  • Select an option

  • Save Quaese/4f08fd52d6c7ebbe98d6e12ac4d32073 to your computer and use it in GitHub Desktop.

Select an option

Save Quaese/4f08fd52d6c7ebbe98d6e12ac4d32073 to your computer and use it in GitHub Desktop.
JavaScript modulo
/*
* As method on Number prototype
* (slower, see: https://jsperf.app/negative-modulo/2)
*
* Code:
Number.prototype.mod = function (n) {
"use strict";
return ((this % n) + n) % n;
};
*
* Example:
* 2 % 3 => 2.mod(3) = 2
*/
// Better use: mod(2, 3) = 2
const mod = (n, m) => {
return ((n % m) + m) % m;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment