Skip to content

Instantly share code, notes, and snippets.

@jgeryk
Created January 12, 2017 20:30
Show Gist options
  • Select an option

  • Save jgeryk/7407dd15650ad53ca09327d9581b2215 to your computer and use it in GitHub Desktop.

Select an option

Save jgeryk/7407dd15650ad53ca09327d9581b2215 to your computer and use it in GitHub Desktop.
/**
* Maintains a sum of 100(%) in an array by updating the remaining values in relative proportion when one value is changed.
* @function balance
* @param {array} array - array of numbers who sum to 100(%)
* @param {number} index - The index of the number in the array whose value was changed.
* @param {number} oldPct - The previous value of the changed number.
*/
function balance(array, index, oldPct){
var div = 1 - oldPct / 100
var balancedPct = array[index]
for(var i=0; i<array.length; i++){
if (i != index) array[i] = 100 * (((1 - (balancedPct / 100)) * (array[i] / 100)) / div);
}
return array
}
array = [50,50]
array2 = [25,25,25,25]
array[0] = 25
array2[1] = 70
console.log(balance(array, 0, 50))
console.log(balance(array2, 1, 25))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment