Skip to content

Instantly share code, notes, and snippets.

@swinton
Created August 8, 2012 20:59
Show Gist options
  • Save swinton/3298731 to your computer and use it in GitHub Desktop.
Save swinton/3298731 to your computer and use it in GitHub Desktop.
Function to generate a percentage calculator.
// Function to generate a percentage calculator.
// Percentages will be rounded to nearest whole number.
// The calculator ensures the entire set of percentages adds up to 100.
var percentageCalculatorGenerator = function(numDataPoints, total) {
// Ensure cumulative total adds up to 100
var cumulativeTotal = 0;
// Return the generated function
return function(value, idx) {
if (idx + 1 === numDataPoints) {
// Last data point, just make the whole set adds up to 100
return 100 - cumulativeTotal;
} else {
// Calculate the actual percentage for other data points
var pc = Math.round(value / total * 100);
// Record the cumulative total
cumulativeTotal += pc;
// Return the percentage
return pc;
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment