33 */
44import { usePrevious } from '@woocommerce/base-hooks' ;
55
6- export const usePriceConstraint = ( price ) => {
7- const currentConstraint = isNaN ( price )
8- ? null
9- : Math . floor ( parseInt ( price , 10 ) / 10 ) * 10 ;
6+ /**
7+ * Internal dependencies
8+ */
9+ import { ROUND_UP , ROUND_DOWN } from './constants' ;
10+
11+ /**
12+ * Return the price constraint.
13+ *
14+ * @param {number } price Price in minor unit, e.g. cents.
15+ * @param {number } minorUnit Price minor unit (number of digits after the decimal separator).
16+ * @param {ROUND_UP|ROUND_DOWN } direction Rounding flag whether we round up or down.
17+ */
18+ export const usePriceConstraint = ( price , minorUnit , direction ) => {
19+ const step = 10 * 10 ** minorUnit ;
20+ let currentConstraint ;
21+ if ( direction === ROUND_UP ) {
22+ currentConstraint = isNaN ( price )
23+ ? null
24+ : Math . ceil ( parseFloat ( price , 10 ) / step ) * step ;
25+ } else if ( direction === ROUND_DOWN ) {
26+ currentConstraint = isNaN ( price )
27+ ? null
28+ : Math . floor ( parseFloat ( price , 10 ) / step ) * step ;
29+ }
30+
1031 const previousConstraint = usePrevious ( currentConstraint , ( val ) =>
1132 Number . isFinite ( val )
1233 ) ;
@@ -15,9 +36,9 @@ export const usePriceConstraint = ( price ) => {
1536 : previousConstraint ;
1637} ;
1738
18- export default ( { minPrice, maxPrice } ) => {
39+ export default ( { minPrice, maxPrice, minorUnit } ) => {
1940 return {
20- minConstraint : usePriceConstraint ( minPrice ) ,
21- maxConstraint : usePriceConstraint ( maxPrice ) ,
41+ minConstraint : usePriceConstraint ( minPrice , minorUnit , ROUND_DOWN ) ,
42+ maxConstraint : usePriceConstraint ( maxPrice , minorUnit , ROUND_UP ) ,
2243 } ;
2344} ;
0 commit comments