Created
June 26, 2019 10:41
-
-
Save alanrsoares/5b0b53c43e039fd34362dfe9e7ee4cd8 to your computer and use it in GitHub Desktop.
Multiplication with no multiplication, using range reduce
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
const isInt = n => parseInt(n) === n; | |
const toPrecisionN = precision => n => | |
Number((n).toPrecision(precision)); | |
function multiplyInt(a, b) { | |
const iterable = [...new Array(Math.abs(Math.floor(a)))]; | |
return iterable.reduce( | |
acc => a < 0 | |
? acc - b | |
: acc + b, | |
0 | |
); | |
} | |
function multiply(a, b, acc = undefined) { | |
if (isInt(b) && !isInt(a)) { | |
// invert operands for algorhythmic short-circuit | |
return multiplyInt(b, a, acc); | |
} | |
const precision = 5; | |
const toPrecision = toPrecisionN(precision); | |
const intProduct = multiplyInt(a, b, acc); | |
if (!isInt(a)) { | |
const rest = parseInt(a) - a; | |
const precisionFactor = Math.pow(10, precision); | |
const restProduct = multiplyInt(rest * precisionFactor, b); | |
const absRestProduct = Math.abs(restProduct / precisionFactor); | |
return toPrecision(intProduct + absRestProduct); | |
} else { | |
return toPrecision(intProduct); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment