Skip to content

Instantly share code, notes, and snippets.

@lukealbao
Created July 11, 2017 15:39
Show Gist options
  • Save lukealbao/59e3bdc44586bdc85c1f175374336eb3 to your computer and use it in GitHub Desktop.
Save lukealbao/59e3bdc44586bdc85c1f175374336eb3 to your computer and use it in GitHub Desktop.
Format some percentages
// 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