Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.