Skip to content

Clamp

Clamps a number between a minimum and maximum number.

๐ŸŽฌ Usage

<script>
    import {clamp} from "@sveu/shared/math"
    let min = 0

    let max = 100

    let value = 50

    $: result = clamp(value, min, max)

</script>

<h1>{result}</h1>

<label for="min">Min</label>
<input type="number" bind:value="{min}" id="min">

<label for="max">Max</label>
<input type="number" bind:value="{max}" id="max">

<label for="value">Value</label>
<input type="number" bind:value="{value}" id="value">

๐Ÿ‘ฉโ€๐Ÿ’ปAPI

๐Ÿ‘ป Arguments

Name Description Type Required
value The number to clamp. number Yes
min The minimum number to clamp. number Yes
max The maximum number to clamp. number Yes

โ†ฉ๏ธ Returns

A number between the minimum and maximum number.

๐Ÿงช Playground

Source Code ๐Ÿ‘€

Source Code
/**
 * Clamp a value between two other values.
 *
 * @param value - The value to clamp
 *
 * @param min - The minimum value
 *
 * @param max - The maximum value
 *
 * @returns The clamped value
 */
export function clamp(value: number, min: number, max: number): number {
    return Math.min(max, Math.max(min, value))
}

Last update: 2023-02-14