@wpgenius/financial-calculators 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { readNumber, toMonths, yearlySeries } from '../utils.js';
1
+ import { readNumber, readStartYear, toMonths, yearlySeries } from '../utils.js';
2
2
 
3
3
  /**
4
4
  * SWP (systematic withdrawal plan): a fixed amount withdrawn at the start of
@@ -11,17 +11,19 @@ import { readNumber, toMonths, yearlySeries } from '../utils.js';
11
11
  * @param {number} inputs.monthlyWithdrawal Amount withdrawn each month.
12
12
  * @param {number} inputs.annualRate Expected return, % a year.
13
13
  * @param {number} inputs.years Duration in years (fractions allowed).
14
+ * @param {number} [inputs.startYear] Optional calendar year of the start; series points get calendarYear.
14
15
  * @return {{investment: number, totalWithdrawn: number, finalBalance: number,
15
16
  * returns: number, depletedMonth: (number|null), months: number,
16
17
  * series: Array<{year: number, month: number, balance: number, withdrawn: number}>}}
17
18
  * returns = finalBalance + totalWithdrawn − investment.
18
19
  * depletedMonth is the month (1-based) the balance reached zero, or null.
19
20
  */
20
- export function swp( { investment, monthlyWithdrawal, annualRate, years } ) {
21
+ export function swp( { investment, monthlyWithdrawal, annualRate, years, startYear } ) {
21
22
  const start = readNumber( 'investment', investment );
22
23
  const withdrawal = readNumber( 'monthlyWithdrawal', monthlyWithdrawal );
23
24
  const i = readNumber( 'annualRate', annualRate ) / 100 / 12;
24
25
  const months = toMonths( years );
26
+ const firstYear = readStartYear( startYear );
25
27
 
26
28
  const balances = [ start ];
27
29
  const withdrawnTotals = [ 0 ];
@@ -55,6 +57,6 @@ export function swp( { investment, monthlyWithdrawal, annualRate, years } ) {
55
57
  series: yearlySeries( months, ( month ) => ( {
56
58
  balance: balances[ month ],
57
59
  withdrawn: withdrawnTotals[ month ],
58
- } ) ),
60
+ } ), firstYear ),
59
61
  };
60
62
  }
@@ -10,6 +10,24 @@ const LOCALES = { indian: 'en-IN', international: 'en-US' };
10
10
  let intlChecked = false;
11
11
  let intlWorks = false;
12
12
 
13
+ // One formatter per locale and decimals: sliders format many values per frame,
14
+ // and building an Intl.NumberFormat is far slower than using one.
15
+ const formatters = new Map();
16
+
17
+ function formatter( system, decimals ) {
18
+ const key = system + ':' + decimals;
19
+ let cached = formatters.get( key );
20
+ if ( ! cached ) {
21
+ cached = new Intl.NumberFormat( LOCALES[ system ], {
22
+ minimumFractionDigits: decimals,
23
+ maximumFractionDigits: decimals,
24
+ useGrouping: true,
25
+ } );
26
+ formatters.set( key, cached );
27
+ }
28
+ return cached;
29
+ }
30
+
13
31
  function canUseIntl() {
14
32
  if ( ! intlChecked ) {
15
33
  intlChecked = true;
@@ -82,11 +100,7 @@ export function formatNumber( value, { system = 'indian', decimals = 0 } = {} )
82
100
  const rounded = Number( value.toFixed( decimals ) );
83
101
  const number = rounded === 0 ? 0 : value;
84
102
  if ( canUseIntl() ) {
85
- return new Intl.NumberFormat( LOCALES[ system ], {
86
- minimumFractionDigits: decimals,
87
- maximumFractionDigits: decimals,
88
- useGrouping: true,
89
- } ).format( number );
103
+ return formatter( system, decimals ).format( number );
90
104
  }
91
105
  return formatByHand( number, decimals, system );
92
106
  }
@@ -2,75 +2,140 @@
2
2
  * Amounts in words, in the Indian (lakh, crore) or international (million,
3
3
  * billion...) system, with no limit on size: above the largest named unit
4
4
  * the words repeat ("One Thousand Crore", "One Thousand Decillion").
5
+ *
6
+ * The words are English by default; pass `words` to use your own (for
7
+ * translations). The structure stays the same: hundreds, then tens and ones,
8
+ * then the unit name.
9
+ */
10
+
11
+ const ENGLISH = {
12
+ ones: [ '', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',
13
+ 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen',
14
+ 'Eighteen', 'Nineteen' ],
15
+ tens: [ '', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety' ],
16
+ hundred: 'Hundred',
17
+ and: 'and',
18
+ zero: 'Zero',
19
+ minus: 'Minus',
20
+ indian: { thousand: 'Thousand', lakh: 'Lakh', crore: 'Crore' },
21
+ international: [ '', 'Thousand', 'Million', 'Billion', 'Trillion', 'Quadrillion',
22
+ 'Quintillion', 'Sextillion', 'Septillion', 'Octillion', 'Nonillion', 'Decillion' ],
23
+ };
24
+
25
+ const STRING_KEYS = [ 'hundred', 'and', 'zero', 'minus' ];
26
+
27
+ /**
28
+ * Merges custom words with the English defaults and checks their shape.
29
+ *
30
+ * @param {Object} [custom] Partial words object.
31
+ * @return {Object} A complete words object.
5
32
  */
33
+ function readWords( custom ) {
34
+ if ( custom === undefined ) {
35
+ return ENGLISH;
36
+ }
37
+ if ( ! custom || typeof custom !== 'object' ) {
38
+ throw new TypeError( 'words must be an object.' );
39
+ }
40
+ const list = ( key, length ) => {
41
+ if ( custom[ key ] === undefined ) {
42
+ return ENGLISH[ key ];
43
+ }
44
+ const value = custom[ key ];
45
+ if ( ! Array.isArray( value ) || value.length !== length || ! value.every( ( w ) => typeof w === 'string' ) ) {
46
+ throw new TypeError( `words.${ key } must be an array of ${ length } strings.` );
47
+ }
48
+ return value;
49
+ };
50
+ const words = {
51
+ ones: list( 'ones', 20 ),
52
+ tens: list( 'tens', 10 ),
53
+ international: list( 'international', ENGLISH.international.length ),
54
+ indian: { ...ENGLISH.indian },
55
+ };
56
+ for ( const key of STRING_KEYS ) {
57
+ if ( custom[ key ] !== undefined && typeof custom[ key ] !== 'string' ) {
58
+ throw new TypeError( `words.${ key } must be a string.` );
59
+ }
60
+ words[ key ] = custom[ key ] ?? ENGLISH[ key ];
61
+ }
62
+ if ( custom.indian !== undefined ) {
63
+ if ( ! custom.indian || typeof custom.indian !== 'object' ) {
64
+ throw new TypeError( 'words.indian must be an object with thousand, lakh and crore.' );
65
+ }
66
+ for ( const key of Object.keys( ENGLISH.indian ) ) {
67
+ if ( custom.indian[ key ] !== undefined ) {
68
+ if ( typeof custom.indian[ key ] !== 'string' ) {
69
+ throw new TypeError( `words.indian.${ key } must be a string.` );
70
+ }
71
+ words.indian[ key ] = custom.indian[ key ];
72
+ }
73
+ }
74
+ }
75
+ return words;
76
+ }
6
77
 
7
- const ONES = [ '', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',
8
- 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen',
9
- 'Eighteen', 'Nineteen' ];
10
- const TENS = [ '', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety' ];
11
- const INTERNATIONAL_SCALES = [ '', 'Thousand', 'Million', 'Billion', 'Trillion', 'Quadrillion',
12
- 'Quintillion', 'Sextillion', 'Septillion', 'Octillion', 'Nonillion', 'Decillion' ];
78
+ function join( parts ) {
79
+ return parts.filter( Boolean ).join( ' ' );
80
+ }
13
81
 
14
82
  // 0–99.
15
- function belowHundred( n ) {
83
+ function belowHundred( n, w ) {
16
84
  if ( n < 20 ) {
17
- return ONES[ n ];
85
+ return w.ones[ n ];
18
86
  }
19
- return [ TENS[ Math.floor( n / 10 ) ], ONES[ n % 10 ] ].filter( Boolean ).join( ' ' );
87
+ return join( [ w.tens[ Math.floor( n / 10 ) ], w.ones[ n % 10 ] ] );
20
88
  }
21
89
 
22
90
  // 0–999: "Four Hundred and Seventy Seven".
23
- function belowThousand( n ) {
91
+ function belowThousand( n, w ) {
24
92
  const hundreds = Math.floor( n / 100 );
25
93
  const rest = n % 100;
26
94
  if ( ! hundreds ) {
27
- return belowHundred( rest );
95
+ return belowHundred( rest, w );
28
96
  }
29
- return `${ ONES[ hundreds ] } Hundred` + ( rest ? ` and ${ belowHundred( rest ) }` : '' );
30
- }
31
-
32
- function join( parts ) {
33
- return parts.filter( Boolean ).join( ' ' );
97
+ return join( [ w.ones[ hundreds ], w.hundred, rest ? w.and : '', rest ? belowHundred( rest, w ) : '' ] );
34
98
  }
35
99
 
36
100
  // Digits → words, Indian system: ...crore, lakh, thousand, hundreds.
37
- function indian( digits ) {
101
+ function indian( digits, w ) {
38
102
  digits = digits.replace( /^0+/, '' );
39
103
  if ( digits === '' ) {
40
104
  return '';
41
105
  }
42
106
  if ( digits.length > 7 ) {
43
- const crores = indian( digits.slice( 0, -7 ) );
44
- return join( [ crores && `${ crores } Crore`, indian( digits.slice( -7 ) ) ] );
107
+ const crores = indian( digits.slice( 0, -7 ), w );
108
+ return join( [ crores && `${ crores } ${ w.indian.crore }`, indian( digits.slice( -7 ), w ) ] );
45
109
  }
46
110
  const n = Number( digits );
47
111
  const lakh = Math.floor( n / 1e5 );
48
112
  const thousand = Math.floor( ( n % 1e5 ) / 1e3 );
49
113
  const rest = n % 1e3;
50
114
  return join( [
51
- lakh && `${ belowHundred( lakh ) } Lakh`,
52
- thousand && `${ belowHundred( thousand ) } Thousand`,
53
- belowThousand( rest ),
115
+ lakh && `${ belowHundred( lakh, w ) } ${ w.indian.lakh }`,
116
+ thousand && `${ belowHundred( thousand, w ) } ${ w.indian.thousand }`,
117
+ belowThousand( rest, w ),
54
118
  ] );
55
119
  }
56
120
 
57
121
  // Digits → words, international system: groups of three.
58
- function international( digits ) {
122
+ function international( digits, w ) {
59
123
  digits = digits.replace( /^0+/, '' );
60
124
  if ( digits === '' ) {
61
125
  return '';
62
126
  }
63
- const maxDigits = INTERNATIONAL_SCALES.length * 3;
127
+ const scales = w.international;
128
+ const maxDigits = scales.length * 3;
64
129
  if ( digits.length > maxDigits ) {
65
- const top = international( digits.slice( 0, -( maxDigits - 3 ) ) );
66
- const last = INTERNATIONAL_SCALES[ INTERNATIONAL_SCALES.length - 1 ];
67
- return join( [ top && `${ top } ${ last }`, international( digits.slice( -( maxDigits - 3 ) ) ) ] );
130
+ const top = international( digits.slice( 0, -( maxDigits - 3 ) ), w );
131
+ const last = scales[ scales.length - 1 ];
132
+ return join( [ top && `${ top } ${ last }`, international( digits.slice( -( maxDigits - 3 ) ), w ) ] );
68
133
  }
69
134
  const parts = [];
70
135
  for ( let end = digits.length, scale = 0; end > 0; end -= 3, scale++ ) {
71
136
  const group = Number( digits.slice( Math.max( 0, end - 3 ), end ) );
72
137
  if ( group ) {
73
- parts.unshift( join( [ belowThousand( group ), INTERNATIONAL_SCALES[ scale ] ] ) );
138
+ parts.unshift( join( [ belowThousand( group, w ), scales[ scale ] ] ) );
74
139
  }
75
140
  }
76
141
  return join( parts );
@@ -83,12 +148,17 @@ function international( digits ) {
83
148
  * digits (for amounts beyond 2^53).
84
149
  * @param {Object} [options]
85
150
  * @param {string} [options.system='indian'] "indian" or "international".
151
+ * @param {Object} [options.words] Your own words, merged with the English ones:
152
+ * ones (20 strings, 0–19), tens (10 strings), hundred, and ('' to leave it out),
153
+ * zero, minus, indian { thousand, lakh, crore }, international (12 strings:
154
+ * '', thousand, million … decillion).
86
155
  * @return {string} e.g. 2808477 → "Twenty Eight Lakh Eight Thousand Four Hundred and Seventy Seven".
87
156
  */
88
- export function amountInWords( value, { system = 'indian' } = {} ) {
157
+ export function amountInWords( value, { system = 'indian', words } = {} ) {
89
158
  if ( system !== 'indian' && system !== 'international' ) {
90
159
  throw new RangeError( `system must be "indian" or "international", got "${ system }".` );
91
160
  }
161
+ const w = readWords( words );
92
162
  let digits;
93
163
  let negative = false;
94
164
  if ( typeof value === 'number' ) {
@@ -109,9 +179,9 @@ export function amountInWords( value, { system = 'indian' } = {} ) {
109
179
  throw new TypeError( `value must be a number, a BigInt or a string of digits, got ${ String( value ) }.` );
110
180
  }
111
181
 
112
- const words = system === 'indian' ? indian( digits ) : international( digits );
113
- if ( words === '' ) {
114
- return 'Zero';
182
+ const text = system === 'indian' ? indian( digits, w ) : international( digits, w );
183
+ if ( text === '' ) {
184
+ return w.zero;
115
185
  }
116
- return negative ? `Minus ${ words }` : words;
186
+ return negative ? join( [ w.minus, text ] ) : text;
117
187
  }
package/src/utils.js CHANGED
@@ -37,20 +37,43 @@ export function toMonths( years ) {
37
37
  return months;
38
38
  }
39
39
 
40
+ /**
41
+ * Reads the optional startYear input: a whole calendar year, or undefined.
42
+ *
43
+ * @param {*} startYear
44
+ * @return {(number|undefined)}
45
+ */
46
+ export function readStartYear( startYear ) {
47
+ if ( startYear === undefined || startYear === null || startYear === '' ) {
48
+ return undefined;
49
+ }
50
+ const year = readNumber( 'startYear', startYear, -1e6 );
51
+ if ( ! Number.isInteger( year ) ) {
52
+ throw new RangeError( `startYear must be a whole year, got ${ startYear }.` );
53
+ }
54
+ return year;
55
+ }
56
+
40
57
  /**
41
58
  * Builds a chart series with one point per year (month 0, 12, 24...), plus
42
59
  * the last month when the duration is not a whole number of years.
43
60
  *
44
- * @param {number} months Duration in months.
45
- * @param {function(number): Object} point Values at a given month.
46
- * @return {Array<Object>} Points: { year, month, ...point(month) }.
61
+ * @param {number} months Duration in months.
62
+ * @param {function(number): Object} point Values at a given month.
63
+ * @param {number} [startYear] Calendar year of month 0; adds calendarYear.
64
+ * @return {Array<Object>} Points: { year, month, [calendarYear], ...point(month) }.
47
65
  */
48
- export function yearlySeries( months, point ) {
66
+ export function yearlySeries( months, point, startYear ) {
67
+ const at = ( month ) => {
68
+ const year = month / 12;
69
+ const base = startYear === undefined ? { year, month } : { year, month, calendarYear: startYear + year };
70
+ return { ...base, ...point( month ) };
71
+ };
49
72
  const series = [];
50
73
  for ( let month = 0; month < months; month += 12 ) {
51
- series.push( { year: month / 12, month, ...point( month ) } );
74
+ series.push( at( month ) );
52
75
  }
53
- series.push( { year: months / 12, month: months, ...point( months ) } );
76
+ series.push( at( months ) );
54
77
  return series;
55
78
  }
56
79
 
@@ -10,9 +10,16 @@ export type NumberSystem = 'indian' | 'international';
10
10
  export interface SeriesPoint {
11
11
  year: number;
12
12
  month: number;
13
+ /** startYear + year, when the calculator got a startYear. */
14
+ calendarYear?: number;
13
15
  }
14
16
 
15
- export interface SipInputs {
17
+ /** Optional input on every calculator: the calendar year of the start (such as 2026). */
18
+ export interface StartYearInput {
19
+ startYear?: NumericInput;
20
+ }
21
+
22
+ export interface SipInputs extends StartYearInput {
16
23
  /** Amount invested at the start of every month. */
17
24
  monthlyAmount: NumericInput;
18
25
  /** Expected return, % a year (12 for 12%). */
@@ -34,7 +41,7 @@ export interface SipResult {
34
41
  series: GrowthPoint[];
35
42
  }
36
43
 
37
- export interface LumpsumInputs {
44
+ export interface LumpsumInputs extends StartYearInput {
38
45
  /** Amount invested once, at the start. */
39
46
  amount: NumericInput;
40
47
  annualRate: NumericInput;
@@ -45,7 +52,7 @@ export interface LumpsumInputs {
45
52
 
46
53
  export type LumpsumResult = SipResult;
47
54
 
48
- export interface SwpInputs {
55
+ export interface SwpInputs extends StartYearInput {
49
56
  /** Amount invested at the start. */
50
57
  investment: NumericInput;
51
58
  /** Amount withdrawn at the start of every month. */
@@ -73,7 +80,7 @@ export interface SwpResult {
73
80
  series: SwpPoint[];
74
81
  }
75
82
 
76
- export interface GoalInputs {
83
+ export interface GoalInputs extends StartYearInput {
77
84
  /** What the goal costs today. */
78
85
  presentCost: NumericInput;
79
86
  /** Savings already put aside for it (default 0). */
@@ -102,10 +109,12 @@ export interface GoalResult {
102
109
  monthlyInvestment: number;
103
110
  totalInvested: number;
104
111
  months: number;
112
+ /** startYear + years, when a startYear was given. */
113
+ targetYear?: number;
105
114
  series: GoalPoint[];
106
115
  }
107
116
 
108
- export interface EmiInputs {
117
+ export interface EmiInputs extends StartYearInput {
109
118
  /** Loan amount. */
110
119
  principal: NumericInput;
111
120
  /** Interest, % a year. */
@@ -194,8 +203,29 @@ export function formatCurrency( value: number, options?: CurrencyOptions ): stri
194
203
  export function formatCompact( value: number, options?: CompactOptions ): string;
195
204
  /** groupDigits( '1234567' ) → "12,34,567". */
196
205
  export function groupDigits( digits: string, system?: NumberSystem ): string;
206
+ /** Your own words for amountInWords (for translations). Missing keys fall back to English. */
207
+ export interface WordsOptions {
208
+ /** 20 strings for 0–19 (index 0 is unused, usually ''). */
209
+ ones?: string[];
210
+ /** 10 strings: '', '', twenty … ninety. */
211
+ tens?: string[];
212
+ hundred?: string;
213
+ /** Between hundreds and the rest ("and"); '' leaves it out. */
214
+ and?: string;
215
+ zero?: string;
216
+ minus?: string;
217
+ indian?: { thousand?: string; lakh?: string; crore?: string };
218
+ /** 12 strings: '', thousand, million … decillion. */
219
+ international?: string[];
220
+ }
221
+
222
+ export interface AmountInWordsOptions {
223
+ system?: NumberSystem;
224
+ words?: WordsOptions;
225
+ }
226
+
197
227
  /** amountInWords( 2808477 ) → "Twenty Eight Lakh Eight Thousand Four Hundred and Seventy Seven". */
198
- export function amountInWords( value: number | bigint | string, options?: { system?: NumberSystem } ): string;
228
+ export function amountInWords( value: number | bigint | string, options?: AmountInWordsOptions ): string;
199
229
 
200
230
  /** Library version, e.g. "1.0.0". */
201
231
  export const VERSION: string;