Skip to content

Instantly share code, notes, and snippets.

@remarcable
Created February 16, 2018 12:19
Show Gist options
  • Save remarcable/b3a416504d6b4a262f25bbe5f7869555 to your computer and use it in GitHub Desktop.
Save remarcable/b3a416504d6b4a262f25bbe5f7869555 to your computer and use it in GitHub Desktop.
Modulo and Division Operator
function mod(x1, x2) {
if (Math.floor(x1) !== x1 || Math.floor(x2) !== x2) { throw new Error("no floats, please :)"); }
while (x1 >= x2) {
x1 -= x2;
}
return x1;
}
function div(x1, x2) {
if (Math.floor(x1) !== x1 || Math.floor(x2) !== x2) { throw new Error("no floats, please :)"); }
let counter = 0;
while (x1 >= x2) {
counter += 1;
x1 -= x2;
}
return counter;
}
// TESTS
console.log("|| MOD ||");
console.log(mod(10, 2) === 0, mod(10, 2), '===', 0);
console.log(mod(11, 2) === 1, mod(11, 2), '===', 1);
console.log(mod(0, 2) === 0, mod(0, 2), '===', 0);
console.log(mod(10, 3) === 1, mod(10, 3), '===', 1);
console.log(mod(11, 3) === 2, mod(11, 3), '===', 2);
console.log(mod(12, 3) === 0, mod(12, 3), '===', 0);
console.log(mod(50, 26) === 24, mod(50, 26), '===', 24);
try {
mod(10.5, 2);
console.log("error not working");
} catch (e) {
console.log("error working");
}
console.log("\n|| DIV ||");
console.log(div(10, 2) === 5, div(10, 2), '===', 5);
console.log(div(11, 2) === 5, div(11, 2), '===', 5);
console.log(div(0, 2) === 0, div(0, 2), '===', 0);
console.log(div(10, 3) === 3, div(10, 3), '===', 3);
console.log(div(11, 3) === 3, div(11, 3), '===', 3);
console.log(div(12, 3) === 4, div(12, 3), '===', 4);
console.log(div(50, 26) === 1, div(50, 26), '===', 1);
try {
div(10, 2.2);
console.log("error not working");
} catch (e) {
console.log("error working");
}
// run in node using `node mod-div.js` or paste into browser console
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment