Skip to content

Commit

Permalink
multiply accepts multiple numerical strings as an array
Browse files Browse the repository at this point in the history
  • Loading branch information
DanielJDufour committed Nov 20, 2022
1 parent 3e82ea5 commit ffb0248
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 16 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,10 @@ import multiply from "preciso/multiply.js";

multiply("-714.7008086132632", "8135.725531"); // -714.7008086132632 * 8135.725531
"-5814609.6156612701214627592"

// pass in an array of numerical strings
multiply(["2", "3", "4"]);
"24"
```

### pow (power)
Expand Down
31 changes: 15 additions & 16 deletions multiply.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,27 @@ const clean = require("./clean.js");
const compare_positive = require("./compare_positive.js");
const long_multiplication = require("./long_multiplication.js");

function multiply(a, b) {
a = clean(a);
b = clean(b);
function multiply() {
const nums = Array.isArray(arguments[0]) ? arguments[0] : arguments;

const apos = a[0] !== "-";
const bpos = b[0] !== "-";
let product = clean(nums[0]);
let product_absolute = absolute(product);
let product_sign = product[0] === "-" ? "-" : "";

const out_sign = apos !== bpos ? "-" : "";
const imax = nums.length;
for (let i = 1; i < imax; i++) {
const current = clean(nums[i]);
const current_sign = current[0] === "-" ? "-" : "";
const current_absolute = absolute(current);
product_sign = product_sign !== current_sign ? "-" : "";

a = absolute(a);
b = absolute(b);
const comparison = compare_positive(product_absolute, current_absolute);

const comparison = compare_positive(a, b);
product_absolute = comparison === "<" ? long_multiplication(current_absolute, product_absolute) : long_multiplication(product_absolute, current_absolute);

if (comparison === "<") {
const aold = a;
const bold = b;
a = bold;
b = aold;
product = product_sign + product_absolute;
}

return out_sign + long_multiplication(a, b);
return product;
}

module.exports = multiply;
Expand Down

0 comments on commit ffb0248

Please sign in to comment.