rate
The rate utility calculates the percentage of a value relative to a total. It is a simple but essential tool for generating progress indicators, statistics, or normalized values.
Implementation
View Source Code
ts
/**
* Creates an array of numbers progressing from min to max with a specified number of steps.
*
* @example
* ```ts
* const min = 0;
* const max = 10;
* const steps = 5;
*
* rate(min, max, steps) // [0, 2.5, 5, 7.5, 10];
* ```
*
* @param min - The start of the range.
* @param max - The end of the range.
* @param [steps=5] - The number of steps between min and max.
*
* @returns The range of numbers.
*/
export function rate(min: number, max: number, steps = 5) {
if (steps === 1) return [min];
const stepSize = (max - min) / (steps - 1);
return Array.from({ length: steps }, (_, i) => min + i * stepSize);
}Features
- Isomorphic: Works in both Browser and Node.js.
- Safe Division: Handles cases where the total is zero by returning
0instead ofInfinity. - Type-safe: Properly typed for numeric inputs and results.
API
ts
function rate(value: number, total: number, decimals?: number): number;Parameters
value: The part or current value.total: The whole or maximum value.
Returns
- A number representing the rate (between
0and100ifvalue <= total).
Examples
Basic Progress
ts
import { rate } from '@vielzeug/toolkit';
rate(50, 100); // 50
rate(1, 4); // 25
rate(3, 10); // 30Safety with Zero
ts
import { rate } from '@vielzeug/toolkit';
// Prevents division by zero errors
rate(10, 0); // 0Implementation Notes
- Returns
(value / total) * 100. - Returns
0iftotalis zero to preventNaNorInfinityresults. - Does not automatically round the result; use the
roundutility if precision is needed.
See Also
- round: Round the calculated rate to a specific precision.
- clamp: Ensure the rate stays within a
0-100range ifvalue > total. - average: Calculate the mean of multiple rates.