Created
August 8, 2012 20:59
-
-
Save swinton/3298731 to your computer and use it in GitHub Desktop.
Function to generate a percentage calculator.
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
// 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