Last active
April 18, 2018 18:50
-
-
Save deadkff01/ff6f776d10077f007d9be126e0da8651 to your computer and use it in GitHub Desktop.
JavaScript divide function without using "/"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Multiplication and division rules... ((+)*(+)=+) ((-)*(-)=+) ((+)*(-)=-) ((-)*(+)=-) | |
const multiply = (x, y) => { | |
let r = Math.exp(Math.log(Math.abs(x)) + Math.log(Math.abs(y))).toFixed(2) | |
return Number((x < 0 && y < 0) ? r : (x < 0 || y < 0) ? -r : r) | |
} | |
const divide = (x, y) => { | |
return (x === 0) ? 0 : multiply(((multiply(x, y) < 0) ? -1.0 : 1.0), Math.exp(Math.log(Math.abs(x)) - Math.log(Math.abs(y)))) | |
} | |
// result -66.6 | |
console.log(divide(-133.2, 2)) | |
// result 2.5 | |
console.log(divide(5, 2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
const divide = (x, y) => x * y ** -1;