Skip to content

Instantly share code, notes, and snippets.

@winfamy
Last active September 6, 2018 15:08
Show Gist options
  • Save winfamy/2a592cee116e3288c820d0cf20167dc3 to your computer and use it in GitHub Desktop.
Save winfamy/2a592cee116e3288c820d0cf20167dc3 to your computer and use it in GitHub Desktop.
Modulo Solutions (JS)
function modBySubtract(num, modBy) {
// floor truncates a decimal on a double
// num/modBy = 20/3 = 6.6667
// floor(num/modBy) = 6
// so we're finding the total full count of modBy within num
// then subtracting to find the remainder
// will throw a divideByZero runtime error if modBy = 0
let fullAmountCount = Math.floor(num/modBy)
return num - modBy*fullAmountCount
}
function modByMod(num, modBy) {
// equivalent of this in MATLAB
// mod(num, modBy) - https://www.mathworks.com/help/matlab/ref/mod.html
return num % modBy
}
function modByLoop(num, modBy) {
// the reason I don't do any checks if num > 0
// is that num >= modBy will catch anything
// and !modBy returns if modBy is a null or 0 value
// which would cause an infinite loop
if (!modBy) return num
while (num >= modBy) {
num -= modBy
}
return num
}
console.log(`modBySubtract: ${modBySubtract(20, 3)}`)
console.log(`modBySubtract: ${modBySubtract(2*Math.PI+Math.PI/6, 2*Math.PI)}`)
// Outputs
// modBySubtract: 2
// modBySubtract: 0.5235987755982991
console.log(`modByMod: ${modByMod(20, 3)}`)
console.log(`modByMod: ${modByMod(2*Math.PI+Math.PI/6, 2*Math.PI)}`)
// Outputs
// modByMod: 2
// modByMod: 0.5235987755982991
console.log(`modByLoop: ${modByLoop(20, 3)}`)
console.log(`modByLoop: ${modByLoop(2*Math.PI+Math.PI/6, 2*Math.PI)}`)
// Outputs
// modByLoop: 2
// modByLoop: 0.5235987755982991
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment