Add and Remove percentage proportionally

3

Doubt is in mathematics, a calculation that will be used in a program.

Let's say I have 3 items with different percentages:

Item 1 - 10%
Item 2 - 40%
Item 3 - 50%

I want to remove for example 10% of Item 3 and distribute this percentage in the other two proportionally, generating the following result:

Item 1 - 12%
Item 2 - 48%
Item 3 - 40%

Does anyone have any idea of the calculation or how do I get to this result?

    
asked by anonymous 08.05.2014 / 23:59

1 answer

2

Test like this:

var items = {
    item1: 10,
    item2: 40,
    item3: 50
};

function distribuir(el, qtd) {

    var somaTotal = 0,
        nrItems = 0;
    for (var este in items) {
        if (items[el] != items[este]) {
            somaTotal += items[este];
            nrItems++;
        }

    }

    for (var este in items) {
        if (items[el] != items[este]) {
            if (somaTotal == 0) items[este] += qtd / nrItems;
            else items[este] += (items[este] || 1) * qtd / somaTotal;
        } else items[este] -= qtd;
    }
    return items;
}
distribuir('item3', 10); // dá Object {item1: 12, item2: 48, item3: 40} 

Example

    
09.05.2014 / 00:33