@@ -18,33 +18,38 @@ export function clamp(value: number, min: number = -Infinity, max: number = Infi
18
18
return newValue ;
19
19
}
20
20
21
+ export function roundToStepPrecision ( value : number , step : number ) {
22
+ let roundedValue = value ;
23
+ let stepString = step . toString ( ) ;
24
+ let pointIndex = stepString . indexOf ( '.' ) ;
25
+ let precision = pointIndex >= 0 ? stepString . length - pointIndex : 0 ;
26
+ if ( precision > 0 ) {
27
+ let pow = Math . pow ( 10 , precision ) ;
28
+ roundedValue = Math . round ( roundedValue * pow ) / pow ;
29
+ }
30
+ return roundedValue ;
31
+ }
32
+
21
33
export function snapValueToStep ( value : number , min : number | undefined , max : number | undefined , step : number ) : number {
22
34
min = Number ( min ) ;
23
35
max = Number ( max ) ;
24
36
let remainder = ( ( value - ( isNaN ( min ) ? 0 : min ) ) % step ) ;
25
- let snappedValue = Math . abs ( remainder ) * 2 >= step
37
+ let snappedValue = roundToStepPrecision ( Math . abs ( remainder ) * 2 >= step
26
38
? value + Math . sign ( remainder ) * ( step - Math . abs ( remainder ) )
27
- : value - remainder ;
39
+ : value - remainder , step ) ;
28
40
29
41
if ( ! isNaN ( min ) ) {
30
42
if ( snappedValue < min ) {
31
43
snappedValue = min ;
32
44
} else if ( ! isNaN ( max ) && snappedValue > max ) {
33
- snappedValue = min + Math . floor ( ( max - min ) / step ) * step ;
45
+ snappedValue = min + Math . floor ( roundToStepPrecision ( ( max - min ) / step , step ) ) * step ;
34
46
}
35
47
} else if ( ! isNaN ( max ) && snappedValue > max ) {
36
- snappedValue = Math . floor ( max / step ) * step ;
48
+ snappedValue = Math . floor ( roundToStepPrecision ( max / step , step ) ) * step ;
37
49
}
38
50
39
51
// correct floating point behavior by rounding to step precision
40
- let string = step . toString ( ) ;
41
- let index = string . indexOf ( '.' ) ;
42
- let precision = index >= 0 ? string . length - index : 0 ;
43
-
44
- if ( precision > 0 ) {
45
- let pow = Math . pow ( 10 , precision ) ;
46
- snappedValue = Math . round ( snappedValue * pow ) / pow ;
47
- }
52
+ snappedValue = roundToStepPrecision ( snappedValue , step ) ;
48
53
49
54
return snappedValue ;
50
55
}
0 commit comments