Skip to content

Instantly share code, notes, and snippets.

@E01T
Last active February 5, 2020 09:24
Show Gist options
  • Save E01T/bc213caba3d67ff9c53ce97562121e18 to your computer and use it in GitHub Desktop.
Save E01T/bc213caba3d67ff9c53ce97562121e18 to your computer and use it in GitHub Desktop.
Correct Modulo in JavaScript
// From https://stackoverflow.com/questions/10063546/modulo-for-negative-dividends-in-python?noredirect=1&lq=1
// a % b = a - (a // b) * b
const divMod = (a, b) => {
return a - Math.floor(a / b) * b;
}
for (let i = 0; i < 20; i++) {
console.log(divMod(i, 10));
}
console.log('Negatives');
for (let i = -20; i < 0; i++) {
console.log(divMod(i, 10));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment