1+ class PriceCalculator {
2+ constructor ( config = { } ) {
3+ this . typeDiscounts = config . typeDiscounts || {
4+ 1 : 0 ,
5+ 2 : 0.1 ,
6+ 3 : 0.3 ,
7+ 4 : 0.5
8+ } ;
9+ this . maxYearsDiscount = config . maxYearsDiscount || 5 ;
10+ this . yearlyDiscountRate = config . yearlyDiscountRate || 0.01 ; // 1% per year
11+ }
12+
13+ calculate ( amount , type , years ) {
14+ try {
15+ this . validateInputs ( amount , type , years ) ;
16+
17+ const baseDiscount = this . typeDiscounts [ type ] ;
18+ const yearsDiscount = Math . min ( years , this . maxYearsDiscount ) * this . yearlyDiscountRate ;
19+
20+ const basePrice = amount * ( 1 - baseDiscount ) ;
21+ const yearlyDiscount = basePrice * yearsDiscount ;
22+
23+ const finalPrice = basePrice - yearlyDiscount ;
24+ return Number ( finalPrice . toFixed ( 2 ) ) ; // Round to 2 decimal places
25+ } catch ( error ) {
26+ console . error ( 'Calculation error:' , error . message ) ;
27+ throw error ;
28+ }
29+ }
30+
31+ validateInputs ( amount , type , years ) {
32+ if ( typeof amount !== 'number' || isNaN ( amount ) || amount < 0 ) {
33+ throw new Error ( 'Amount must be a non-negative number' ) ;
34+ }
35+ if ( ! Number . isInteger ( type ) || ! this . typeDiscounts . hasOwnProperty ( type ) ) {
36+ throw new Error ( `Type must be one of: ${ Object . keys ( this . typeDiscounts ) . join ( ', ' ) } ` ) ;
37+ }
38+ if ( ! Number . isInteger ( years ) || years < 0 ) {
39+ throw new Error ( 'Years must be a non-negative integer' ) ;
40+ }
41+ }
42+ }
43+
44+ module . exports = PriceCalculator ;
0 commit comments