Skip to content

Instantly share code, notes, and snippets.

@deadkff01
Last active April 18, 2018 18:50
Show Gist options
  • Save deadkff01/ff6f776d10077f007d9be126e0da8651 to your computer and use it in GitHub Desktop.
Save deadkff01/ff6f776d10077f007d9be126e0da8651 to your computer and use it in GitHub Desktop.
JavaScript divide function without using "/"
// 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))
@ankr
Copy link

ankr commented Feb 25, 2018

const divide = (x, y) => x * y ** -1;

@deadkff01
Copy link
Author

This works well too 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment