normalizeNumber
Normalizes a number within a given range to a value between 0 and 1.
1/**
2 * Normalizes a number within a given range to a value between 0 and 1.
3 *
4 * @param value - The input number.
5 * @param min - The minimum value of the range.
6 * @param max - The maximum value of the range.
7 * @returns A normalized number between 0 and 1.
8 */
9export function normalizeNumber(value: number, min: number, max: number): number {
10 if (min === max) return 0;
11 return (value - min) / (max - min);
12}
Standardized Output
Transforms any number into a normalized range
[0, 1]
, making it suitable for further scaling or comparison.Graceful Handling of Degenerate Range
Returns
0
whenmin === max
to avoid division by zero, improving robustness.Mathematically Accurate
Implements classic normalization logic used in statistics, graphics, and machine learning.
Minimal and Efficient
Straightforward arithmetic ensures fast execution and high readability.
Tests | Examples
1test('normalizeNumber - within range', () => {
2 expect(normalizeNumber(75, 50, 100)).toBe(0.5);
3});
4
5test('normalizeNumber - min boundary', () => {
6 expect(normalizeNumber(0, 0, 100)).toBe(0);
7});
8
9test('normalizeNumber - max boundary', () => {
10 expect(normalizeNumber(100, 0, 100)).toBe(1);
11});
12
13test('normalizeNumber - below range', () => {
14 expect(normalizeNumber(-50, 0, 100)).toBe(-0.5);
15});
16
17test('normalizeNumber - above range', () => {
18 expect(normalizeNumber(150, 0, 100)).toBe(1.5);
19});
20
21test('normalizeNumber - zero range', () => {
22 expect(normalizeNumber(5, 5, 5)).toBe(0);
23});
Common Use Cases
Data Normalization for ML/AI
Normalize input features for machine learning models that expect values between 0 and 1.
UI Progress or Animation Mapping
Convert values into percentages for use in sliders, progress bars, or animation easing.
Statistical Analysis
Normalize data points for comparison, visualization, or standard score calculation.
Game Mechanics and Physics
Scale values (e.g., health, speed, energy) proportionally for simulations or effects.
Audio/Video Processing
Normalize input levels or signal values before applying filters or effects.