Created
November 3, 2014 12:03
-
-
Save filippomangione/0695c8825190954ce0f2 to your computer and use it in GitHub Desktop.
Add Up to 100%
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
var _ = require('./underscore.js'); | |
function foo(l, target) { | |
var off = target - _.reduce(l, function(acc, x) { return acc + Math.round(x) }, 0); | |
return _.chain(l). | |
sortBy(function(x) { return Math.round(x) - x }). | |
map(function(x, i) { return Math.round(x) + (off > i) - (i >= (l.length + off)) }). | |
value(); | |
} | |
foo([13.626332, 47.989636, 9.596008, 28.788024], 100) // => [48, 29, 14, 9] | |
foo([16.666, 16.666, 16.666, 16.666, 16.666, 16.666], 100) // => [17, 17, 17, 17, 16, 16] | |
foo([33.333, 33.333, 33.333], 100) // => [34, 33, 33] | |
foo([33.3, 33.3, 33.3, 0.1], 100) // => [34, 33, 33, 0] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment