@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.
package/README.md CHANGED
@@ -78,7 +78,7 @@ the [latest release](https://github.com/wpgenius/financial-calculators-js/releas
78
78
  | `formatNumber( value, { system, decimals } )` | `"58,08,477"` or `"5,808,477"` |
79
79
  | `formatCurrency( value, { symbol, position, system, decimals } )` | `"₹58,08,477"`, `"1,500 €"` |
80
80
  | `formatCompact( value, { system, decimals } )` | `"15L"`, `"2.5Cr"`, `"1.5M"` |
81
- | `amountInWords( value, { system } )` | `"Fifty Eight Lakh …"` |
81
+ | `amountInWords( value, { system, words } )` | `"Fifty Eight Lakh …"`, or in your own words |
82
82
  | `groupDigits( digits, system )`, `VERSION` | Hand-made grouping; the library version |
83
83
 
84
84
  The details follow; the [documentation](https://wpgenius.github.io/financial-calculators-js/docs.html) has the same with more examples.
@@ -95,6 +95,10 @@ Each result has `months` and a `series`: one point at month 0, 12, 24... and a
95
95
  last point at the final month, each with `year` and `month` plus the values
96
96
  listed below.
97
97
 
98
+ Every calculator also takes an optional `startYear` (such as `2026`): each
99
+ series point then gets `calendarYear` (`startYear + year`), handy for chart
100
+ labels, and `goal()` also returns `targetYear`.
101
+
98
102
  #### `sip( { monthlyAmount, annualRate, years } )`
99
103
 
100
104
  Same amount invested at the start of every month, compounded monthly.
@@ -159,13 +163,23 @@ register( 'myCalc', ( inputs ) => ( { … } ) ); // add or replace a calculator
159
163
  | `formatNumber( value, { system, decimals = 0 } )` | `formatNumber( 5808477 )` → `"58,08,477"` |
160
164
  | `formatCurrency( value, { symbol = '₹', position = 'before', system, decimals = 0 } )` | `formatCurrency( -1500 )` → `"-₹1,500"`; `position: 'after'` → `"1,500 €"` |
161
165
  | `formatCompact( value, { system, decimals = 1 } )` | `formatCompact( 1500000 )` → `"15L"`; international → `"1.5M"` |
162
- | `amountInWords( value, { system } )` | `amountInWords( 1e12 )` → `"One Lakh Crore"` |
166
+ | `amountInWords( value, { system, words } )` | `amountInWords( 1e12 )` → `"One Lakh Crore"` |
163
167
  | `groupDigits( digits, system )` | `groupDigits( '1234567' )` → `"12,34,567"` |
164
168
 
165
169
  `formatNumber` uses `Intl.NumberFormat` when the runtime has the `en-IN`
166
170
  locale, and the same grouping by hand otherwise. `amountInWords` rounds to a
167
171
  whole number and also takes a `BigInt` or a string of digits for amounts
168
- beyond 2^53. `VERSION` is the library version.
172
+ beyond 2^53. Pass `words` to translate it: any of `ones` (20 strings), `tens` (10),
173
+ `hundred`, `and` (`''` to leave it out), `zero`, `minus`, `indian`
174
+ (`{ thousand, lakh, crore }`) and `international` (12 strings); missing keys
175
+ stay English.
176
+
177
+ ```js
178
+ amountInWords( 150000, { words: {
179
+ ones: [ '', 'एक', 'दो', /* … */ ], tens: [ '', '', 'बीस', /* … */ ],
180
+ hundred: 'सौ', and: '', indian: { thousand: 'हज़ार', lakh: 'लाख', crore: 'करोड़' },
181
+ } } ); // "एक लाख पचास हज़ार"
182
+ ``` `VERSION` is the library version.
169
183
 
170
184
  ## Contributing
171
185
 
@@ -1,4 +1,4 @@
1
- /*! financial-calculators 1.0.0 | GPL-3.0-or-later | https://wpgenius.github.io/financial-calculators-js/ */
1
+ /*! financial-calculators 1.1.0 | GPL-3.0-or-later | https://wpgenius.github.io/financial-calculators-js/ */
2
2
 
3
3
  // src/utils.js
4
4
  function readNumber(name, value, min = 0) {
@@ -18,12 +18,27 @@ function toMonths(years) {
18
18
  }
19
19
  return months;
20
20
  }
21
- function yearlySeries(months, point) {
21
+ function readStartYear(startYear) {
22
+ if (startYear === void 0 || startYear === null || startYear === "") {
23
+ return void 0;
24
+ }
25
+ const year = readNumber("startYear", startYear, -1e6);
26
+ if (!Number.isInteger(year)) {
27
+ throw new RangeError(`startYear must be a whole year, got ${startYear}.`);
28
+ }
29
+ return year;
30
+ }
31
+ function yearlySeries(months, point, startYear) {
32
+ const at = (month) => {
33
+ const year = month / 12;
34
+ const base = startYear === void 0 ? { year, month } : { year, month, calendarYear: startYear + year };
35
+ return { ...base, ...point(month) };
36
+ };
22
37
  const series = [];
23
38
  for (let month = 0; month < months; month += 12) {
24
- series.push({ year: month / 12, month, ...point(month) });
39
+ series.push(at(month));
25
40
  }
26
- series.push({ year: months / 12, month: months, ...point(months) });
41
+ series.push(at(months));
27
42
  return series;
28
43
  }
29
44
  function annuityDueValue(amount, i, n) {
@@ -34,10 +49,11 @@ function annuityDueValue(amount, i, n) {
34
49
  }
35
50
 
36
51
  // src/calculators/sip.js
37
- function sip({ monthlyAmount, annualRate, years }) {
52
+ function sip({ monthlyAmount, annualRate, years, startYear }) {
38
53
  const amount = readNumber("monthlyAmount", monthlyAmount);
39
54
  const i = readNumber("annualRate", annualRate) / 100 / 12;
40
55
  const months = toMonths(years);
56
+ const firstYear = readStartYear(startYear);
41
57
  const total = annuityDueValue(amount, i, months);
42
58
  const invested = amount * months;
43
59
  return {
@@ -48,15 +64,16 @@ function sip({ monthlyAmount, annualRate, years }) {
48
64
  series: yearlySeries(months, (month) => ({
49
65
  invested: amount * month,
50
66
  total: annuityDueValue(amount, i, month)
51
- }))
67
+ }), firstYear)
52
68
  };
53
69
  }
54
70
 
55
71
  // src/calculators/lumpsum.js
56
- function lumpsum({ amount, annualRate, years, compoundingPerYear = 1 }) {
72
+ function lumpsum({ amount, annualRate, years, compoundingPerYear = 1, startYear }) {
57
73
  const invested = readNumber("amount", amount);
58
74
  const rate = readNumber("annualRate", annualRate) / 100;
59
75
  const months = toMonths(years);
76
+ const firstYear = readStartYear(startYear);
60
77
  const k = readNumber("compoundingPerYear", compoundingPerYear, 1);
61
78
  const valueAt = (month) => invested * Math.pow(1 + rate / k, k * month / 12);
62
79
  const total = valueAt(months);
@@ -68,16 +85,17 @@ function lumpsum({ amount, annualRate, years, compoundingPerYear = 1 }) {
68
85
  series: yearlySeries(months, (month) => ({
69
86
  invested,
70
87
  total: valueAt(month)
71
- }))
88
+ }), firstYear)
72
89
  };
73
90
  }
74
91
 
75
92
  // src/calculators/swp.js
76
- function swp({ investment, monthlyWithdrawal, annualRate, years }) {
93
+ function swp({ investment, monthlyWithdrawal, annualRate, years, startYear }) {
77
94
  const start = readNumber("investment", investment);
78
95
  const withdrawal = readNumber("monthlyWithdrawal", monthlyWithdrawal);
79
96
  const i = readNumber("annualRate", annualRate) / 100 / 12;
80
97
  const months = toMonths(years);
98
+ const firstYear = readStartYear(startYear);
81
99
  const balances = [start];
82
100
  const withdrawnTotals = [0];
83
101
  let balance = start;
@@ -108,17 +126,18 @@ function swp({ investment, monthlyWithdrawal, annualRate, years }) {
108
126
  series: yearlySeries(months, (month) => ({
109
127
  balance: balances[month],
110
128
  withdrawn: withdrawnTotals[month]
111
- }))
129
+ }), firstYear)
112
130
  };
113
131
  }
114
132
 
115
133
  // src/calculators/goal.js
116
- function goal({ presentCost, currentSavings = 0, inflationRate, annualRate, years }) {
134
+ function goal({ presentCost, currentSavings = 0, inflationRate, annualRate, years, startYear }) {
117
135
  const cost = readNumber("presentCost", presentCost);
118
136
  const savings = readNumber("currentSavings", currentSavings);
119
137
  const inflation = readNumber("inflationRate", inflationRate) / 100;
120
138
  const rate = readNumber("annualRate", annualRate) / 100;
121
139
  const months = toMonths(years);
140
+ const firstYear = readStartYear(startYear);
122
141
  const i = rate / 12;
123
142
  const costAt = (month) => cost * Math.pow(1 + inflation, month / 12);
124
143
  const savingsAt = (month) => savings * Math.pow(1 + rate, month / 12);
@@ -134,6 +153,7 @@ function goal({ presentCost, currentSavings = 0, inflationRate, annualRate, year
134
153
  monthlyInvestment,
135
154
  totalInvested: monthlyInvestment * months,
136
155
  months,
156
+ ...firstYear === void 0 ? {} : { targetYear: firstYear + months / 12 },
137
157
  series: yearlySeries(months, (month) => {
138
158
  const investments = annuityDueValue(monthlyInvestment, i, month);
139
159
  return {
@@ -142,15 +162,16 @@ function goal({ presentCost, currentSavings = 0, inflationRate, annualRate, year
142
162
  investments,
143
163
  total: savingsAt(month) + investments
144
164
  };
145
- })
165
+ }, firstYear)
146
166
  };
147
167
  }
148
168
 
149
169
  // src/calculators/emi.js
150
- function emi({ principal, annualRate, years }) {
170
+ function emi({ principal, annualRate, years, startYear }) {
151
171
  const loan = readNumber("principal", principal);
152
172
  const i = readNumber("annualRate", annualRate) / 100 / 12;
153
173
  const months = toMonths(years);
174
+ const firstYear = readStartYear(startYear);
154
175
  const instalment = i === 0 ? loan / months : loan * i * Math.pow(1 + i, months) / (Math.pow(1 + i, months) - 1);
155
176
  const balances = [loan];
156
177
  const principalPaid = [0];
@@ -186,7 +207,7 @@ function emi({ principal, annualRate, years }) {
186
207
  balance: balances[month],
187
208
  principalPaid: principalPaid[month],
188
209
  interestPaid: interestPaid[month]
189
- }))
210
+ }), firstYear)
190
211
  };
191
212
  }
192
213
 
@@ -212,6 +233,20 @@ function register(type, fn) {
212
233
  var LOCALES = { indian: "en-IN", international: "en-US" };
213
234
  var intlChecked = false;
214
235
  var intlWorks = false;
236
+ var formatters = /* @__PURE__ */ new Map();
237
+ function formatter(system, decimals) {
238
+ const key = system + ":" + decimals;
239
+ let cached = formatters.get(key);
240
+ if (!cached) {
241
+ cached = new Intl.NumberFormat(LOCALES[system], {
242
+ minimumFractionDigits: decimals,
243
+ maximumFractionDigits: decimals,
244
+ useGrouping: true
245
+ });
246
+ formatters.set(key, cached);
247
+ }
248
+ return cached;
249
+ }
215
250
  function canUseIntl() {
216
251
  if (!intlChecked) {
217
252
  intlChecked = true;
@@ -260,11 +295,7 @@ function formatNumber(value, { system = "indian", decimals = 0 } = {}) {
260
295
  const rounded = Number(value.toFixed(decimals));
261
296
  const number = rounded === 0 ? 0 : value;
262
297
  if (canUseIntl()) {
263
- return new Intl.NumberFormat(LOCALES[system], {
264
- minimumFractionDigits: decimals,
265
- maximumFractionDigits: decimals,
266
- useGrouping: true
267
- }).format(number);
298
+ return formatter(system, decimals).format(number);
268
299
  }
269
300
  return formatByHand(number, decimals, system);
270
301
  }
@@ -297,103 +328,157 @@ function formatCompact(value, { system = "indian", decimals = 1 } = {}) {
297
328
  }
298
329
 
299
330
  // src/format/words.js
300
- var ONES = [
301
- "",
302
- "One",
303
- "Two",
304
- "Three",
305
- "Four",
306
- "Five",
307
- "Six",
308
- "Seven",
309
- "Eight",
310
- "Nine",
311
- "Ten",
312
- "Eleven",
313
- "Twelve",
314
- "Thirteen",
315
- "Fourteen",
316
- "Fifteen",
317
- "Sixteen",
318
- "Seventeen",
319
- "Eighteen",
320
- "Nineteen"
321
- ];
322
- var TENS = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"];
323
- var INTERNATIONAL_SCALES = [
324
- "",
325
- "Thousand",
326
- "Million",
327
- "Billion",
328
- "Trillion",
329
- "Quadrillion",
330
- "Quintillion",
331
- "Sextillion",
332
- "Septillion",
333
- "Octillion",
334
- "Nonillion",
335
- "Decillion"
336
- ];
337
- function belowHundred(n) {
331
+ var ENGLISH = {
332
+ ones: [
333
+ "",
334
+ "One",
335
+ "Two",
336
+ "Three",
337
+ "Four",
338
+ "Five",
339
+ "Six",
340
+ "Seven",
341
+ "Eight",
342
+ "Nine",
343
+ "Ten",
344
+ "Eleven",
345
+ "Twelve",
346
+ "Thirteen",
347
+ "Fourteen",
348
+ "Fifteen",
349
+ "Sixteen",
350
+ "Seventeen",
351
+ "Eighteen",
352
+ "Nineteen"
353
+ ],
354
+ tens: ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"],
355
+ hundred: "Hundred",
356
+ and: "and",
357
+ zero: "Zero",
358
+ minus: "Minus",
359
+ indian: { thousand: "Thousand", lakh: "Lakh", crore: "Crore" },
360
+ international: [
361
+ "",
362
+ "Thousand",
363
+ "Million",
364
+ "Billion",
365
+ "Trillion",
366
+ "Quadrillion",
367
+ "Quintillion",
368
+ "Sextillion",
369
+ "Septillion",
370
+ "Octillion",
371
+ "Nonillion",
372
+ "Decillion"
373
+ ]
374
+ };
375
+ var STRING_KEYS = ["hundred", "and", "zero", "minus"];
376
+ function readWords(custom) {
377
+ if (custom === void 0) {
378
+ return ENGLISH;
379
+ }
380
+ if (!custom || typeof custom !== "object") {
381
+ throw new TypeError("words must be an object.");
382
+ }
383
+ const list = (key, length) => {
384
+ if (custom[key] === void 0) {
385
+ return ENGLISH[key];
386
+ }
387
+ const value = custom[key];
388
+ if (!Array.isArray(value) || value.length !== length || !value.every((w) => typeof w === "string")) {
389
+ throw new TypeError(`words.${key} must be an array of ${length} strings.`);
390
+ }
391
+ return value;
392
+ };
393
+ const words = {
394
+ ones: list("ones", 20),
395
+ tens: list("tens", 10),
396
+ international: list("international", ENGLISH.international.length),
397
+ indian: { ...ENGLISH.indian }
398
+ };
399
+ for (const key of STRING_KEYS) {
400
+ if (custom[key] !== void 0 && typeof custom[key] !== "string") {
401
+ throw new TypeError(`words.${key} must be a string.`);
402
+ }
403
+ words[key] = custom[key] ?? ENGLISH[key];
404
+ }
405
+ if (custom.indian !== void 0) {
406
+ if (!custom.indian || typeof custom.indian !== "object") {
407
+ throw new TypeError("words.indian must be an object with thousand, lakh and crore.");
408
+ }
409
+ for (const key of Object.keys(ENGLISH.indian)) {
410
+ if (custom.indian[key] !== void 0) {
411
+ if (typeof custom.indian[key] !== "string") {
412
+ throw new TypeError(`words.indian.${key} must be a string.`);
413
+ }
414
+ words.indian[key] = custom.indian[key];
415
+ }
416
+ }
417
+ }
418
+ return words;
419
+ }
420
+ function join(parts) {
421
+ return parts.filter(Boolean).join(" ");
422
+ }
423
+ function belowHundred(n, w) {
338
424
  if (n < 20) {
339
- return ONES[n];
425
+ return w.ones[n];
340
426
  }
341
- return [TENS[Math.floor(n / 10)], ONES[n % 10]].filter(Boolean).join(" ");
427
+ return join([w.tens[Math.floor(n / 10)], w.ones[n % 10]]);
342
428
  }
343
- function belowThousand(n) {
429
+ function belowThousand(n, w) {
344
430
  const hundreds = Math.floor(n / 100);
345
431
  const rest = n % 100;
346
432
  if (!hundreds) {
347
- return belowHundred(rest);
433
+ return belowHundred(rest, w);
348
434
  }
349
- return `${ONES[hundreds]} Hundred` + (rest ? ` and ${belowHundred(rest)}` : "");
350
- }
351
- function join(parts) {
352
- return parts.filter(Boolean).join(" ");
435
+ return join([w.ones[hundreds], w.hundred, rest ? w.and : "", rest ? belowHundred(rest, w) : ""]);
353
436
  }
354
- function indian(digits) {
437
+ function indian(digits, w) {
355
438
  digits = digits.replace(/^0+/, "");
356
439
  if (digits === "") {
357
440
  return "";
358
441
  }
359
442
  if (digits.length > 7) {
360
- const crores = indian(digits.slice(0, -7));
361
- return join([crores && `${crores} Crore`, indian(digits.slice(-7))]);
443
+ const crores = indian(digits.slice(0, -7), w);
444
+ return join([crores && `${crores} ${w.indian.crore}`, indian(digits.slice(-7), w)]);
362
445
  }
363
446
  const n = Number(digits);
364
447
  const lakh = Math.floor(n / 1e5);
365
448
  const thousand = Math.floor(n % 1e5 / 1e3);
366
449
  const rest = n % 1e3;
367
450
  return join([
368
- lakh && `${belowHundred(lakh)} Lakh`,
369
- thousand && `${belowHundred(thousand)} Thousand`,
370
- belowThousand(rest)
451
+ lakh && `${belowHundred(lakh, w)} ${w.indian.lakh}`,
452
+ thousand && `${belowHundred(thousand, w)} ${w.indian.thousand}`,
453
+ belowThousand(rest, w)
371
454
  ]);
372
455
  }
373
- function international(digits) {
456
+ function international(digits, w) {
374
457
  digits = digits.replace(/^0+/, "");
375
458
  if (digits === "") {
376
459
  return "";
377
460
  }
378
- const maxDigits = INTERNATIONAL_SCALES.length * 3;
461
+ const scales = w.international;
462
+ const maxDigits = scales.length * 3;
379
463
  if (digits.length > maxDigits) {
380
- const top = international(digits.slice(0, -(maxDigits - 3)));
381
- const last = INTERNATIONAL_SCALES[INTERNATIONAL_SCALES.length - 1];
382
- return join([top && `${top} ${last}`, international(digits.slice(-(maxDigits - 3)))]);
464
+ const top = international(digits.slice(0, -(maxDigits - 3)), w);
465
+ const last = scales[scales.length - 1];
466
+ return join([top && `${top} ${last}`, international(digits.slice(-(maxDigits - 3)), w)]);
383
467
  }
384
468
  const parts = [];
385
469
  for (let end = digits.length, scale = 0; end > 0; end -= 3, scale++) {
386
470
  const group = Number(digits.slice(Math.max(0, end - 3), end));
387
471
  if (group) {
388
- parts.unshift(join([belowThousand(group), INTERNATIONAL_SCALES[scale]]));
472
+ parts.unshift(join([belowThousand(group, w), scales[scale]]));
389
473
  }
390
474
  }
391
475
  return join(parts);
392
476
  }
393
- function amountInWords(value, { system = "indian" } = {}) {
477
+ function amountInWords(value, { system = "indian", words } = {}) {
394
478
  if (system !== "indian" && system !== "international") {
395
479
  throw new RangeError(`system must be "indian" or "international", got "${system}".`);
396
480
  }
481
+ const w = readWords(words);
397
482
  let digits;
398
483
  let negative = false;
399
484
  if (typeof value === "number") {
@@ -413,15 +498,15 @@ function amountInWords(value, { system = "indian" } = {}) {
413
498
  } else {
414
499
  throw new TypeError(`value must be a number, a BigInt or a string of digits, got ${String(value)}.`);
415
500
  }
416
- const words = system === "indian" ? indian(digits) : international(digits);
417
- if (words === "") {
418
- return "Zero";
501
+ const text = system === "indian" ? indian(digits, w) : international(digits, w);
502
+ if (text === "") {
503
+ return w.zero;
419
504
  }
420
- return negative ? `Minus ${words}` : words;
505
+ return negative ? join([w.minus, text]) : text;
421
506
  }
422
507
 
423
508
  // src/index.js
424
- var VERSION = true ? "1.0.0" : "development";
509
+ var VERSION = true ? "1.1.0" : "development";
425
510
  export {
426
511
  VERSION,
427
512
  amountInWords,