Skip to content
VersionSize

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 0 instead of Infinity.
  • 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 0 and 100 if value <= total).

Examples

Basic Progress

ts
import { rate } from '@vielzeug/toolkit';

rate(50, 100); // 50
rate(1, 4); // 25
rate(3, 10); // 30

Safety with Zero

ts
import { rate } from '@vielzeug/toolkit';

// Prevents division by zero errors
rate(10, 0); // 0

Implementation Notes

  • Returns (value / total) * 100.
  • Returns 0 if total is zero to prevent NaN or Infinity results.
  • Does not automatically round the result; use the round utility if precision is needed.

See Also

  • round: Round the calculated rate to a specific precision.
  • clamp: Ensure the rate stays within a 0-100 range if value > total.
  • average: Calculate the mean of multiple rates.