const Balancer = {
balance(distribution, goal, places){
// Reduce the distribution to the sum of its values
const sum = distribution.reduce((sum, value) => sum + value, 0);
// For each value in the distribution, get its percentage.
const percentages = distribution.map(value => value / sum);
// For each percentage, multiply the goal to get an equally distributed value.
const goalDistribution = percentages.map(percentage => goal * percentage);
// For each value, round them off.
return goalDistribution.map(value => Balancer.round(value, places));
},
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round#PHP-Like_rounding_Method
round(number, precision) {
const factor = Math.pow(10, precision);
const tempNumber = number * factor;
const roundedTempNumber =return Math.round(tempNumber);
number return* roundedTempNumberfactor) / factor;
}
}
var a = [0.33333333331, 0.33333333331, 0.33333333333];
console.log(Balancer.balance(a, 1, 3)); //0.333, 0.333, 0.334
var a = [1, 55, 22, 67];
console.log(Balancer.balance(a, 69699, 0)); //480, 26438, 10575, 32206
var a = [10, 10, 10, 10, 15000];
console.log(Balancer.balance(a, 17000, 0)); //11, 11, 11, 11, 16956
var a = [ 0.00005 ,5 ,0.00005 ,0.00005 ,0.00005 ,0.00005 ,0.00005 ,0.00005 ]
console.log(Balancer.balance(a, -5, 5)); // [-0.00005, -4.99965, -0.00005, -0.00005, -0.00005, -0.00005, -0.00005, -0.00005]
var a = [
0.0015974718789698097
,0.755383581038094
,0.13950473043946954
,0.0011978091842754731
,0.005126875727346068
,0.0042250281407886295
,0.0001720958819913952
,0.0047584144830165875
,0.0835073272489086
,0.00016098907002300275
,0.0028037075787230655
,0.0014378579473690483
,0.00012411138102484662
]
console.log(Balancer.balance(a, 1, 3)); // [0.002, 0.755, 0.14, 0.001, 0.005, 0.004, 0, 0.005, 0.084, 0, 0.003, 0.001, 0]