Created
April 27, 2016 00:35
-
-
Save svyatov/1fbf1f714ebd62b24220f0a1a8c0e1b4 to your computer and use it in GitHub Desktop.
Round percents (lo-dash + coffee)
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
# Based on https://en.wikipedia.org/wiki/Largest_remainder_method | |
roundPercents: (values) -> | |
sum = 0 | |
sumNeeded = 100 | |
percents = _.map values, (value, i) -> | |
quotient = _.floor(value) | |
modulus = value % 1 | |
sum += quotient | |
{ | |
quotient: quotient | |
modulus: modulus | |
originalIndex: i | |
} | |
if sum != sumNeeded | |
percents = _.sortBy(percents, 'modulus').reverse() | |
diff = sumNeeded - sum | |
i = 0 | |
while i < diff | |
percents[i].quotient += 1 | |
i += 1 | |
_.map(_.sortBy(percents, 'originalIndex'), 'quotient') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment