Skip to content

Instantly share code, notes, and snippets.

@bojidaryovchev
Last active November 21, 2020 21:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bojidaryovchev/63f19e0d8a964cd0c3b7b3bb4f74f3c2 to your computer and use it in GitHub Desktop.
Save bojidaryovchev/63f19e0d8a964cd0c3b7b3bb4f74f3c2 to your computer and use it in GitHub Desktop.
function partitionValues(total, minValue, values) {
const percentageByValue = {};
values.filter(v => v > minValue).forEach(v => percentageByValue[v] = v / total * 100);
total -= values.filter(v => v <= minValue).reduce((p, c) => p + c, 0);
const totalPercentage = Object.keys(percentageByValue)
.map(k => percentageByValue[k])
.reduce((prev, curr) => prev + curr, 0);
const ratio = total / totalPercentage;
const partitionedValueByIndex = {};
values.forEach((v, i) => {
if (v > minValue) {
partitionedValueByIndex[i] = ratio * percentageByValue[v];
} else {
partitionedValueByIndex[i] = minValue;
}
})
const partitionedValues = Object.keys(partitionedValueByIndex)
.map(k => partitionedValueByIndex[k]);
if (!partitionedValues.find(v => v < minValue)) {
return partitionedValues;
}
const lowerThanMinValueIndices = [];
partitionedValues.forEach((v, i) => {
if (v < minValue) {
partitionedValues[i] = minValue;
lowerThanMinValueIndices.push(i);
}
});
const delta = lowerThanMinValueIndices.length * minValue;
return this.partitionValues(total - delta, minValue, partitionedValues);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment