-
Notifications
You must be signed in to change notification settings - Fork 0
/
clamp.js
44 lines (38 loc) · 1.03 KB
/
clamp.js
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
/**
* @file Utility that clamps a number to min and max limits inclusive.
* @copyright Copyright (c) 2018-present, Graham Fairweather
* @module clamp
*/
import _clamp from './.internal/_clamp';
import toNumber from './toNumber';
/**
* This method clamps a number to min and max limits inclusive.
*
* @param {number} value - The number to be clamped.
* @param {Array} rest - The remaining arguments array.
* @param {number} [rest.min=0] - The minimum number.
* @param {number} rest.max - The maximum number.
* @throws {RangeError} If min > max.
* @returns {number} The clamped number.
* @example
*
* clamp(-10, -5, 5); // -5
* clamp(10, -5, 5); // 5
*/
export default function clamp(value, ...rest) {
const number = toNumber(value);
const restLength = rest.length;
if (restLength < 1) {
return number;
}
let min = toNumber(rest[0]);
let max = toNumber(rest[1]);
if (restLength < 2) {
max = min;
min = 0;
}
if (min > max) {
throw new RangeError('"min" > "max"');
}
return _clamp(number, min, max);
}