2015-11-24 18:14:24 -05:00
|
|
|
// stolen from http://stackoverflow.com/a/13484088/11983
|
2015-11-30 05:24:25 -05:00
|
|
|
function sumsUpTo100(percentages) {
|
|
|
|
return percentages.map(p => Math.floor(p)).reduce((a, b) => a + b) === 100;
|
|
|
|
}
|
|
|
|
|
2015-11-19 12:23:38 -05:00
|
|
|
export default (percentages) => {
|
2015-11-24 18:14:24 -05:00
|
|
|
const sumOfDecimals = Math.ceil(percentages.map(a => a % 1).reduce((a, b) => a + b));
|
|
|
|
// compensate error by adding 1 to the first n items
|
|
|
|
for (let i = 0; i < sumOfDecimals; i++) {
|
|
|
|
percentages[i] = ++percentages[i];
|
2015-11-30 05:24:25 -05:00
|
|
|
// quit early when there is a rounding issue
|
|
|
|
if (sumsUpTo100(percentages)) break;
|
2015-11-24 18:14:24 -05:00
|
|
|
}
|
2015-11-30 05:24:25 -05:00
|
|
|
return percentages.map(p => Math.floor(p));
|
2015-11-19 12:23:38 -05:00
|
|
|
};
|