ChrisGuru - 1 year ago 67

Javascript Question

this is not a regular JS tasks as I need help with JS and maths little bit. I got the math formula done but now I'm trying to get it in javascript.

I writing a calculator so I got var a,b,c and D.

D is the sum of A,B,C (Currently it is 825)

I changed the D from 825 to 600 so everything should reduce propotionaly but not B. B should stay as it is and A and C should reduce.

The following code below calculate correctly but I want to make it dynamic fully. Var newA and newC I can't seem to get the right variable in it as I need the newA to dive by 6 and New C to divide by 5/6.

Is there any genius good in math and javascript?

I also attached an image of the math formula if anyone can maybe write a better JS.

The idea is if that I can after add more variables and when I reduce the D it will let me know how much are the elements that can be reduced.

Here is the code:

`// Variables`

var a = 100;

var b = 225; // this variable does not change.

var c = 500;

// Container sum

var containerSum = a + b + c ;

// New container sum

var newContainerSum = 600;

// 825 - (100 + 500) = 225

var fixedElement = b;

// 600 - 225 = 375

var remainingElementsTotal = newContainerSum - fixedElement;

//Propotion calculate 100/500 = 1/5 = 0.2

var propotions = a/c;

var remainingPropotions = 1 - propotions;

var newA = remainingElementsTotal/6;

var newC = remainingElementsTotal * (5/6);

Answer Source

Here is a general function that takes the original array of values (`vals`

), the index of the fixed value (`fixedIndex`

), and the new sum (`newSum`

); and returns a new array with suitably modified values:

```
function calc(vals, fixedIndex, newSum) {
var initSum = vals.reduce(function (prev, cur) {return prev + cur;}, 0);
var fixedElement = vals[fixedIndex];
var initRemainingSum = initSum - fixedElement;
var endRemainingSum = newSum - fixedElement;
return vals.map(function(cur, index) {return index === fixedIndex ? cur : endRemainingSum*(cur/initRemainingSum);})
}
```

For example:

```
calc([100, 225, 500], 1, 600)
```

returns:

```
[ 62.5, 225, 312.5 ]
```