Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

mapNumberRange

Maps a number from one range to another.

TypeScript
Copied!
1/**
2 * Maps a number from one range to another.
3 *
4 * @param value - The input number.
5 * @param inMin - The lower bound of the input range.
6 * @param inMax - The upper bound of the input range.
7 * @param outMin - The lower bound of the output range.
8 * @param outMax - The upper bound of the output range.
9 * @returns The value mapped to the new range.
10 */
11export function mapNumberRange(
12  value: number,
13  inMin: number,
14  inMax: number,
15  outMin: number,
16  outMax: number
17): number {
18  if (inMin === inMax) return outMin;
19  return ((value - inMin) / (inMax - inMin)) * (outMax - outMin) + outMin;
20}
  • Flexible Range Mapping

    Converts a number from any input range to any output range, supporting both linear scaling and inversion.

  • Graceful Edge Handling

    Returns outMin if inMin === inMax, preventing division-by-zero and maintaining predictable behavior.

  • Universally Applicable Logic

    Implements a well-known mathematical formula used across many domains like graphics, physics, and statistics.

  • Compact and Performant

    Efficient one-liner formula ensures high speed and readability without sacrificing accuracy.

Tests | Examples

TypeScript
Copied!
1test('mapNumberRange - normal mapping', () => {
2  expect(mapNumberRange(50, 0, 100, 0, 1)).toBe(0.5);
3});
4
5test('mapNumberRange - reverse mapping', () => {
6  expect(mapNumberRange(0.5, 0, 1, 0, 100)).toBe(50);
7});
8
9test('mapNumberRange - input at minimum', () => {
10  expect(mapNumberRange(0, 0, 100, 10, 20)).toBe(10);
11});
12
13test('mapNumberRange - input at maximum', () => {
14  expect(mapNumberRange(100, 0, 100, 10, 20)).toBe(20);
15});
16
17test('mapNumberRange - inverted output range', () => {
18  expect(mapNumberRange(25, 0, 100, 100, 0)).toBe(75);
19});
20
21test('mapNumberRange - zero input range', () => {
22  expect(mapNumberRange(42, 5, 5, 10, 20)).toBe(10);
23});

Common Use Cases

  • UI Transformations

    Map scroll position, mouse movement, or input values to animation progress or layout shifts.

  • Game Development

    Convert health, distance, or score values into scaled effects, speeds, or resource quantities.

  • Data Visualization

    Map raw values to pixel positions, opacity levels, or color intensities on charts or plots.

  • Sensor Calibration

    Rescale hardware readings (e.g., temperature, voltage) to standardized units or output ranges.

  • Audio/Video Control

    Translate user input or signal levels to volume, brightness, or playback speed.

Codebase: Utilities -> Numbers -> mapNumberRange | Yevhen Klymentiev