File tree Expand file tree Collapse file tree 3 files changed +44
-0
lines changed Expand file tree Collapse file tree 3 files changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ import { withinRange } from "../withinRange" ;
2
+
3
+ describe ( "withinRange" , ( ) => {
4
+ it ( "should return the value if the min or max values are undefined" , ( ) => {
5
+ expect ( withinRange ( 100 , undefined , undefined ) ) . toBe ( 100 ) ;
6
+ expect ( withinRange ( 0 , undefined , undefined ) ) . toBe ( 0 ) ;
7
+ expect ( withinRange ( - 100 , undefined , undefined ) ) . toBe ( - 100 ) ;
8
+ } ) ;
9
+
10
+ it ( "should return the correct value based on the min and max values" , ( ) => {
11
+ expect ( withinRange ( 0 , 0 , 10 ) ) . toBe ( 0 ) ;
12
+ expect ( withinRange ( - 1 , 0 , 10 ) ) . toBe ( 0 ) ;
13
+ expect ( withinRange ( - 0.00000001 , 0 , 10 ) ) . toBe ( 0 ) ;
14
+ expect ( withinRange ( 20 , 0 , 20 ) ) . toBe ( 20 ) ;
15
+ expect ( withinRange ( 20 , 0 , 19 ) ) . toBe ( 19 ) ;
16
+ expect ( withinRange ( 10.5 , 10 , 11 ) ) . toBe ( 10.5 ) ;
17
+ expect ( withinRange ( 10.5 , 9 , 10 ) ) . toBe ( 10 ) ;
18
+ } ) ;
19
+ } ) ;
Original file line number Diff line number Diff line change @@ -21,6 +21,7 @@ export * from "./throttle";
21
21
export * from "./loop" ;
22
22
export * from "./getPercentage" ;
23
23
export * from "./nearest" ;
24
+ export * from "./withinRange" ;
24
25
25
26
export * from "./useEnsuredRef" ;
26
27
export * from "./useIsomorphicLayoutEffect" ;
Original file line number Diff line number Diff line change
1
+ /**
2
+ * A simple util that will ensure that a number is within the optional min and max values.
3
+ *
4
+ * @param value The number to ensure that is within the range
5
+ * @param min The optional min value
6
+ * @param max The optional max value
7
+ * @return the updated value
8
+ */
9
+ export function withinRange (
10
+ value : number ,
11
+ min : number | undefined ,
12
+ max : number | undefined
13
+ ) : number {
14
+ let nextValue = value ;
15
+ if ( typeof min === "number" ) {
16
+ nextValue = Math . max ( min , nextValue ) ;
17
+ }
18
+
19
+ if ( typeof max === "number" ) {
20
+ nextValue = Math . min ( max , nextValue ) ;
21
+ }
22
+
23
+ return nextValue ;
24
+ }
You can’t perform that action at this time.
0 commit comments