Last active
November 21, 2020 21:08
-
-
Save bojidaryovchev/63f19e0d8a964cd0c3b7b3bb4f74f3c2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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