JSFiddle - React, Tailwind, and code Playground
by Diana Lemen
JavaScript
function test(weights, except, difference) {
const min = 0;
const max = 100;
const allowed = value => Math.max(Math.min(max, value), min);
const round = value => Number(value.toFixed(2));
let toChange = Object.keys(weights).filter(key => key !== except);
toChange.forEach((key, index) => {
const count = toChange.length - index;
const portion = -round(difference / count);
const prevValue = weights[key];
const value = allowed(weights[key] + portion);
weights[key] = value;
difference += value - prevValue;
if (prevValue === value) {
toChange = toChange.filter(toRemove => toRemove !== key);
}
});
console.log(weights);
}
const weights = {
prob2: 25,
prob3: 25,
prob4: 35,
prob5: 15
};
test(weights, 'prob4', 55);