Created
July 11, 2017 15:39
-
-
Save lukealbao/59e3bdc44586bdc85c1f175374336eb3 to your computer and use it in GitHub Desktop.
Format some percentages
This file contains hidden or 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
// Given a function, integerFormat, that takes an array of numbers and returns a new | |
// array of numbers, like integerFormat([30.1, 60.3, 29.6]) => [30, 60, 30], | |
// you can create a parameterized function to round to any decimal point: | |
function roundToNearest (numbers, resolution) { | |
var leftShift = Math.pow(10, resolution); | |
return integerFormat(numbers.map(n => n * leftShift)).map(n => n / leftShift); | |
} | |
// Assuming integerFormat works something like this: | |
function integerFormat (list) { | |
var ints = list.map(Math.floor); | |
var remainders = list.map(x => x % 1); | |
var maxRemIdx = remainders.map((v, i) => [v, i]).sort((a, b) => b[0] - a[0])[0][1]; | |
return ints.map((x, i) => i === maxRemIdx ? x + 1 : x); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment