agentsqripts
Version:
Comprehensive static code analysis toolkit for identifying technical debt, security vulnerabilities, performance issues, and code quality problems
54 lines (52 loc) • 2.51 kB
JavaScript
/**
* @file Calculate percentage
* @description Single responsibility: Convert value to percentage with safe division
*
* This utility provides a mathematically safe way to calculate percentages while handling
* edge cases like division by zero. The function is used extensively across analyzers
* for scoring, progress tracking, and metrics display.
*
* Design rationale:
* - Zero-division protection prevents runtime errors in analysis pipelines
* - Configurable decimal precision supports different display requirements
* - Returns number type for mathematical operations (not string)
* - Simple interface reduces cognitive load for consumers
*/
/**
* Calculate percentage with safe division and configurable precision
*
* Technical function: Converts a value to percentage of total with division-by-zero protection
*
* Implementation rationale:
* - Early return for zero total prevents division by zero errors
* - toFixed() ensures consistent decimal places for display
* - Number() conversion returns numeric type instead of string for calculations
* - Default 1 decimal place balances precision with readability
*
* Mathematical considerations:
* - Uses standard percentage formula: (value / total) * 100
* - Handles edge case where total = 0 by returning 0 (not NaN or Infinity)
* - Floating point precision controlled by toFixed() to avoid display issues
*
* Edge cases handled:
* - total = 0: Returns 0 to prevent division by zero
* - value > total: Allows >100% results (important for some metrics)
* - Negative values: Supported for delta calculations
* - Non-integer decimals: Handled by toFixed() rounding
*
* Alternative approaches considered:
* - Throwing error on zero division: Rejected as too disruptive for analysis flows
* - Returning null on zero division: Rejected as harder to handle in calculations
* - Using Math.round instead of toFixed: Rejected as less precise for display
*
* @param {number} value - Numerator value to convert to percentage
* @param {number} total - Denominator total value (percentage base)
* @param {number} [decimals=1] - Number of decimal places for precision (0-20)
* @returns {number} Calculated percentage as number (not string)
* @throws {RangeError} If decimals parameter is outside toFixed() range (0-100)
*/
function calculatePercentage(value, total, decimals = 2) {
if (total === 0) return 0;
return Number(((value / total) * 100).toFixed(decimals));
}
module.exports = calculatePercentage;