JSFiddle - React, Tailwind, and code Playground

by Diana Lemen

JavaScript

function applyDifference({ weights, except, difference }) {
console.log({ weights, except, difference });

  const min = 0;
  const max = 1;
  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);

  while(difference && toChange.length) {

    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, 'fdghfdg');
}

  const weights = {
    2: 0.50,
    3: 0.25,
    4: 0.25,
    5: 0
  };
  const difference = "5";
  const except = 4;

applyDifference({ weights, except, difference });