Skip to content

Instantly share code, notes, and snippets.

@svyatov
Created April 27, 2016 00:35
Show Gist options
  • Save svyatov/1fbf1f714ebd62b24220f0a1a8c0e1b4 to your computer and use it in GitHub Desktop.
Save svyatov/1fbf1f714ebd62b24220f0a1a8c0e1b4 to your computer and use it in GitHub Desktop.
Round percents (lo-dash + coffee)
# 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