topogigiovanni
11/16/2016 - 10:16 AM

JavaScript divide function without using "/"

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))