# All files / src/utils getPercentage.ts

100% Statements 56/56
100% Branches 6/6
100% Functions 1/1
100% Lines 56/56

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    571x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    190x
    190x
    16x
    4x
    4x
    4x
    4x
    12x
    16x
    3x
    3x
    16x
    183x
    183x
    183x
    183x
    183x
    183x
     /** @remarks \@since 4.0.1 */
    export interface GetPercentageOptions {
      /**
       * The min value allowed.
       */
      min: number;

      /**
       * The max value allowed.
       */
      max: number;

      /**
       * The current value
       */
      value: number;

      /**
       * Boolean if the min, max, and value options should be validated to make sure
       * they are within the correct range relative to each other.
       *
       * @defaultValue `false`
       */
      validate?: boolean;
    }

    /**
     * Gets the current percentage based on the min, max, and current value.
     *
     * @returns the percentage that the `value` is between the `min` and `max`
     * values.
     *
     * @remarks
     * \@since 4.0.1 uses an object for options instead of multiple arguments.
     * \@since 6.0.0 Updated to be included in the public API and `validate`
     * defaults to `false` instead of `true`.
     */
    export function getPercentage(options: GetPercentageOptions): number {
      const { min, max, value, validate = false } = options;
      if (validate) {
        if (min >= max) {
          throw new RangeError(
            "A range must have the min value less than the max value"
          );
        }

        if (value > max || value < min) {
          throw new RangeError("A value must be between the min and max values");
        }
      }

      const range = max - min;
      const start = value - min;
      const percentage = start / range;
      return Math.max(0, Math.min(Math.abs(percentage), 1));
    }