@wpgenius/financial-calculators 1.0.1 → 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 +17 -3
- package/dist/financial-calculators.esm.js +168 -83
- package/dist/financial-calculators.js +168 -83
- package/dist/financial-calculators.min.js +2 -2
- package/package.json +1 -1
- package/src/calculators/emi.js +5 -3
- package/src/calculators/goal.js +7 -4
- package/src/calculators/lumpsum.js +5 -3
- package/src/calculators/sip.js +5 -3
- package/src/calculators/swp.js +5 -3
- package/src/format/number.js +19 -5
- package/src/format/words.js +103 -33
- package/src/utils.js +29 -6
- package/types/financial-calculators.d.ts +36 -6
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/*! financial-calculators 1.0
|
|
1
|
+
/*! financial-calculators 1.1.0 | GPL-3.0-or-later | https://wpgenius.github.io/financial-calculators-js/ */
|
|
2
2
|
"use strict";
|
|
3
3
|
var FinancialCalculators = (() => {
|
|
4
4
|
var __defProp = Object.defineProperty;
|
|
@@ -56,12 +56,27 @@ var FinancialCalculators = (() => {
|
|
|
56
56
|
}
|
|
57
57
|
return months;
|
|
58
58
|
}
|
|
59
|
-
function
|
|
59
|
+
function readStartYear(startYear) {
|
|
60
|
+
if (startYear === void 0 || startYear === null || startYear === "") {
|
|
61
|
+
return void 0;
|
|
62
|
+
}
|
|
63
|
+
const year = readNumber("startYear", startYear, -1e6);
|
|
64
|
+
if (!Number.isInteger(year)) {
|
|
65
|
+
throw new RangeError(`startYear must be a whole year, got ${startYear}.`);
|
|
66
|
+
}
|
|
67
|
+
return year;
|
|
68
|
+
}
|
|
69
|
+
function yearlySeries(months, point, startYear) {
|
|
70
|
+
const at = (month) => {
|
|
71
|
+
const year = month / 12;
|
|
72
|
+
const base = startYear === void 0 ? { year, month } : { year, month, calendarYear: startYear + year };
|
|
73
|
+
return { ...base, ...point(month) };
|
|
74
|
+
};
|
|
60
75
|
const series = [];
|
|
61
76
|
for (let month = 0; month < months; month += 12) {
|
|
62
|
-
series.push(
|
|
77
|
+
series.push(at(month));
|
|
63
78
|
}
|
|
64
|
-
series.push(
|
|
79
|
+
series.push(at(months));
|
|
65
80
|
return series;
|
|
66
81
|
}
|
|
67
82
|
function annuityDueValue(amount, i, n) {
|
|
@@ -72,10 +87,11 @@ var FinancialCalculators = (() => {
|
|
|
72
87
|
}
|
|
73
88
|
|
|
74
89
|
// src/calculators/sip.js
|
|
75
|
-
function sip({ monthlyAmount, annualRate, years }) {
|
|
90
|
+
function sip({ monthlyAmount, annualRate, years, startYear }) {
|
|
76
91
|
const amount = readNumber("monthlyAmount", monthlyAmount);
|
|
77
92
|
const i = readNumber("annualRate", annualRate) / 100 / 12;
|
|
78
93
|
const months = toMonths(years);
|
|
94
|
+
const firstYear = readStartYear(startYear);
|
|
79
95
|
const total = annuityDueValue(amount, i, months);
|
|
80
96
|
const invested = amount * months;
|
|
81
97
|
return {
|
|
@@ -86,15 +102,16 @@ var FinancialCalculators = (() => {
|
|
|
86
102
|
series: yearlySeries(months, (month) => ({
|
|
87
103
|
invested: amount * month,
|
|
88
104
|
total: annuityDueValue(amount, i, month)
|
|
89
|
-
}))
|
|
105
|
+
}), firstYear)
|
|
90
106
|
};
|
|
91
107
|
}
|
|
92
108
|
|
|
93
109
|
// src/calculators/lumpsum.js
|
|
94
|
-
function lumpsum({ amount, annualRate, years, compoundingPerYear = 1 }) {
|
|
110
|
+
function lumpsum({ amount, annualRate, years, compoundingPerYear = 1, startYear }) {
|
|
95
111
|
const invested = readNumber("amount", amount);
|
|
96
112
|
const rate = readNumber("annualRate", annualRate) / 100;
|
|
97
113
|
const months = toMonths(years);
|
|
114
|
+
const firstYear = readStartYear(startYear);
|
|
98
115
|
const k = readNumber("compoundingPerYear", compoundingPerYear, 1);
|
|
99
116
|
const valueAt = (month) => invested * Math.pow(1 + rate / k, k * month / 12);
|
|
100
117
|
const total = valueAt(months);
|
|
@@ -106,16 +123,17 @@ var FinancialCalculators = (() => {
|
|
|
106
123
|
series: yearlySeries(months, (month) => ({
|
|
107
124
|
invested,
|
|
108
125
|
total: valueAt(month)
|
|
109
|
-
}))
|
|
126
|
+
}), firstYear)
|
|
110
127
|
};
|
|
111
128
|
}
|
|
112
129
|
|
|
113
130
|
// src/calculators/swp.js
|
|
114
|
-
function swp({ investment, monthlyWithdrawal, annualRate, years }) {
|
|
131
|
+
function swp({ investment, monthlyWithdrawal, annualRate, years, startYear }) {
|
|
115
132
|
const start = readNumber("investment", investment);
|
|
116
133
|
const withdrawal = readNumber("monthlyWithdrawal", monthlyWithdrawal);
|
|
117
134
|
const i = readNumber("annualRate", annualRate) / 100 / 12;
|
|
118
135
|
const months = toMonths(years);
|
|
136
|
+
const firstYear = readStartYear(startYear);
|
|
119
137
|
const balances = [start];
|
|
120
138
|
const withdrawnTotals = [0];
|
|
121
139
|
let balance = start;
|
|
@@ -146,17 +164,18 @@ var FinancialCalculators = (() => {
|
|
|
146
164
|
series: yearlySeries(months, (month) => ({
|
|
147
165
|
balance: balances[month],
|
|
148
166
|
withdrawn: withdrawnTotals[month]
|
|
149
|
-
}))
|
|
167
|
+
}), firstYear)
|
|
150
168
|
};
|
|
151
169
|
}
|
|
152
170
|
|
|
153
171
|
// src/calculators/goal.js
|
|
154
|
-
function goal({ presentCost, currentSavings = 0, inflationRate, annualRate, years }) {
|
|
172
|
+
function goal({ presentCost, currentSavings = 0, inflationRate, annualRate, years, startYear }) {
|
|
155
173
|
const cost = readNumber("presentCost", presentCost);
|
|
156
174
|
const savings = readNumber("currentSavings", currentSavings);
|
|
157
175
|
const inflation = readNumber("inflationRate", inflationRate) / 100;
|
|
158
176
|
const rate = readNumber("annualRate", annualRate) / 100;
|
|
159
177
|
const months = toMonths(years);
|
|
178
|
+
const firstYear = readStartYear(startYear);
|
|
160
179
|
const i = rate / 12;
|
|
161
180
|
const costAt = (month) => cost * Math.pow(1 + inflation, month / 12);
|
|
162
181
|
const savingsAt = (month) => savings * Math.pow(1 + rate, month / 12);
|
|
@@ -172,6 +191,7 @@ var FinancialCalculators = (() => {
|
|
|
172
191
|
monthlyInvestment,
|
|
173
192
|
totalInvested: monthlyInvestment * months,
|
|
174
193
|
months,
|
|
194
|
+
...firstYear === void 0 ? {} : { targetYear: firstYear + months / 12 },
|
|
175
195
|
series: yearlySeries(months, (month) => {
|
|
176
196
|
const investments = annuityDueValue(monthlyInvestment, i, month);
|
|
177
197
|
return {
|
|
@@ -180,15 +200,16 @@ var FinancialCalculators = (() => {
|
|
|
180
200
|
investments,
|
|
181
201
|
total: savingsAt(month) + investments
|
|
182
202
|
};
|
|
183
|
-
})
|
|
203
|
+
}, firstYear)
|
|
184
204
|
};
|
|
185
205
|
}
|
|
186
206
|
|
|
187
207
|
// src/calculators/emi.js
|
|
188
|
-
function emi({ principal, annualRate, years }) {
|
|
208
|
+
function emi({ principal, annualRate, years, startYear }) {
|
|
189
209
|
const loan = readNumber("principal", principal);
|
|
190
210
|
const i = readNumber("annualRate", annualRate) / 100 / 12;
|
|
191
211
|
const months = toMonths(years);
|
|
212
|
+
const firstYear = readStartYear(startYear);
|
|
192
213
|
const instalment = i === 0 ? loan / months : loan * i * Math.pow(1 + i, months) / (Math.pow(1 + i, months) - 1);
|
|
193
214
|
const balances = [loan];
|
|
194
215
|
const principalPaid = [0];
|
|
@@ -224,7 +245,7 @@ var FinancialCalculators = (() => {
|
|
|
224
245
|
balance: balances[month],
|
|
225
246
|
principalPaid: principalPaid[month],
|
|
226
247
|
interestPaid: interestPaid[month]
|
|
227
|
-
}))
|
|
248
|
+
}), firstYear)
|
|
228
249
|
};
|
|
229
250
|
}
|
|
230
251
|
|
|
@@ -250,6 +271,20 @@ var FinancialCalculators = (() => {
|
|
|
250
271
|
var LOCALES = { indian: "en-IN", international: "en-US" };
|
|
251
272
|
var intlChecked = false;
|
|
252
273
|
var intlWorks = false;
|
|
274
|
+
var formatters = /* @__PURE__ */ new Map();
|
|
275
|
+
function formatter(system, decimals) {
|
|
276
|
+
const key = system + ":" + decimals;
|
|
277
|
+
let cached = formatters.get(key);
|
|
278
|
+
if (!cached) {
|
|
279
|
+
cached = new Intl.NumberFormat(LOCALES[system], {
|
|
280
|
+
minimumFractionDigits: decimals,
|
|
281
|
+
maximumFractionDigits: decimals,
|
|
282
|
+
useGrouping: true
|
|
283
|
+
});
|
|
284
|
+
formatters.set(key, cached);
|
|
285
|
+
}
|
|
286
|
+
return cached;
|
|
287
|
+
}
|
|
253
288
|
function canUseIntl() {
|
|
254
289
|
if (!intlChecked) {
|
|
255
290
|
intlChecked = true;
|
|
@@ -298,11 +333,7 @@ var FinancialCalculators = (() => {
|
|
|
298
333
|
const rounded = Number(value.toFixed(decimals));
|
|
299
334
|
const number = rounded === 0 ? 0 : value;
|
|
300
335
|
if (canUseIntl()) {
|
|
301
|
-
return
|
|
302
|
-
minimumFractionDigits: decimals,
|
|
303
|
-
maximumFractionDigits: decimals,
|
|
304
|
-
useGrouping: true
|
|
305
|
-
}).format(number);
|
|
336
|
+
return formatter(system, decimals).format(number);
|
|
306
337
|
}
|
|
307
338
|
return formatByHand(number, decimals, system);
|
|
308
339
|
}
|
|
@@ -335,103 +366,157 @@ var FinancialCalculators = (() => {
|
|
|
335
366
|
}
|
|
336
367
|
|
|
337
368
|
// src/format/words.js
|
|
338
|
-
var
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
"",
|
|
363
|
-
"
|
|
364
|
-
"
|
|
365
|
-
"
|
|
366
|
-
"
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
369
|
+
var ENGLISH = {
|
|
370
|
+
ones: [
|
|
371
|
+
"",
|
|
372
|
+
"One",
|
|
373
|
+
"Two",
|
|
374
|
+
"Three",
|
|
375
|
+
"Four",
|
|
376
|
+
"Five",
|
|
377
|
+
"Six",
|
|
378
|
+
"Seven",
|
|
379
|
+
"Eight",
|
|
380
|
+
"Nine",
|
|
381
|
+
"Ten",
|
|
382
|
+
"Eleven",
|
|
383
|
+
"Twelve",
|
|
384
|
+
"Thirteen",
|
|
385
|
+
"Fourteen",
|
|
386
|
+
"Fifteen",
|
|
387
|
+
"Sixteen",
|
|
388
|
+
"Seventeen",
|
|
389
|
+
"Eighteen",
|
|
390
|
+
"Nineteen"
|
|
391
|
+
],
|
|
392
|
+
tens: ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"],
|
|
393
|
+
hundred: "Hundred",
|
|
394
|
+
and: "and",
|
|
395
|
+
zero: "Zero",
|
|
396
|
+
minus: "Minus",
|
|
397
|
+
indian: { thousand: "Thousand", lakh: "Lakh", crore: "Crore" },
|
|
398
|
+
international: [
|
|
399
|
+
"",
|
|
400
|
+
"Thousand",
|
|
401
|
+
"Million",
|
|
402
|
+
"Billion",
|
|
403
|
+
"Trillion",
|
|
404
|
+
"Quadrillion",
|
|
405
|
+
"Quintillion",
|
|
406
|
+
"Sextillion",
|
|
407
|
+
"Septillion",
|
|
408
|
+
"Octillion",
|
|
409
|
+
"Nonillion",
|
|
410
|
+
"Decillion"
|
|
411
|
+
]
|
|
412
|
+
};
|
|
413
|
+
var STRING_KEYS = ["hundred", "and", "zero", "minus"];
|
|
414
|
+
function readWords(custom) {
|
|
415
|
+
if (custom === void 0) {
|
|
416
|
+
return ENGLISH;
|
|
417
|
+
}
|
|
418
|
+
if (!custom || typeof custom !== "object") {
|
|
419
|
+
throw new TypeError("words must be an object.");
|
|
420
|
+
}
|
|
421
|
+
const list = (key, length) => {
|
|
422
|
+
if (custom[key] === void 0) {
|
|
423
|
+
return ENGLISH[key];
|
|
424
|
+
}
|
|
425
|
+
const value = custom[key];
|
|
426
|
+
if (!Array.isArray(value) || value.length !== length || !value.every((w) => typeof w === "string")) {
|
|
427
|
+
throw new TypeError(`words.${key} must be an array of ${length} strings.`);
|
|
428
|
+
}
|
|
429
|
+
return value;
|
|
430
|
+
};
|
|
431
|
+
const words = {
|
|
432
|
+
ones: list("ones", 20),
|
|
433
|
+
tens: list("tens", 10),
|
|
434
|
+
international: list("international", ENGLISH.international.length),
|
|
435
|
+
indian: { ...ENGLISH.indian }
|
|
436
|
+
};
|
|
437
|
+
for (const key of STRING_KEYS) {
|
|
438
|
+
if (custom[key] !== void 0 && typeof custom[key] !== "string") {
|
|
439
|
+
throw new TypeError(`words.${key} must be a string.`);
|
|
440
|
+
}
|
|
441
|
+
words[key] = custom[key] ?? ENGLISH[key];
|
|
442
|
+
}
|
|
443
|
+
if (custom.indian !== void 0) {
|
|
444
|
+
if (!custom.indian || typeof custom.indian !== "object") {
|
|
445
|
+
throw new TypeError("words.indian must be an object with thousand, lakh and crore.");
|
|
446
|
+
}
|
|
447
|
+
for (const key of Object.keys(ENGLISH.indian)) {
|
|
448
|
+
if (custom.indian[key] !== void 0) {
|
|
449
|
+
if (typeof custom.indian[key] !== "string") {
|
|
450
|
+
throw new TypeError(`words.indian.${key} must be a string.`);
|
|
451
|
+
}
|
|
452
|
+
words.indian[key] = custom.indian[key];
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
return words;
|
|
457
|
+
}
|
|
458
|
+
function join(parts) {
|
|
459
|
+
return parts.filter(Boolean).join(" ");
|
|
460
|
+
}
|
|
461
|
+
function belowHundred(n, w) {
|
|
376
462
|
if (n < 20) {
|
|
377
|
-
return
|
|
463
|
+
return w.ones[n];
|
|
378
464
|
}
|
|
379
|
-
return [
|
|
465
|
+
return join([w.tens[Math.floor(n / 10)], w.ones[n % 10]]);
|
|
380
466
|
}
|
|
381
|
-
function belowThousand(n) {
|
|
467
|
+
function belowThousand(n, w) {
|
|
382
468
|
const hundreds = Math.floor(n / 100);
|
|
383
469
|
const rest = n % 100;
|
|
384
470
|
if (!hundreds) {
|
|
385
|
-
return belowHundred(rest);
|
|
471
|
+
return belowHundred(rest, w);
|
|
386
472
|
}
|
|
387
|
-
return
|
|
388
|
-
}
|
|
389
|
-
function join(parts) {
|
|
390
|
-
return parts.filter(Boolean).join(" ");
|
|
473
|
+
return join([w.ones[hundreds], w.hundred, rest ? w.and : "", rest ? belowHundred(rest, w) : ""]);
|
|
391
474
|
}
|
|
392
|
-
function indian(digits) {
|
|
475
|
+
function indian(digits, w) {
|
|
393
476
|
digits = digits.replace(/^0+/, "");
|
|
394
477
|
if (digits === "") {
|
|
395
478
|
return "";
|
|
396
479
|
}
|
|
397
480
|
if (digits.length > 7) {
|
|
398
|
-
const crores = indian(digits.slice(0, -7));
|
|
399
|
-
return join([crores && `${crores}
|
|
481
|
+
const crores = indian(digits.slice(0, -7), w);
|
|
482
|
+
return join([crores && `${crores} ${w.indian.crore}`, indian(digits.slice(-7), w)]);
|
|
400
483
|
}
|
|
401
484
|
const n = Number(digits);
|
|
402
485
|
const lakh = Math.floor(n / 1e5);
|
|
403
486
|
const thousand = Math.floor(n % 1e5 / 1e3);
|
|
404
487
|
const rest = n % 1e3;
|
|
405
488
|
return join([
|
|
406
|
-
lakh && `${belowHundred(lakh)}
|
|
407
|
-
thousand && `${belowHundred(thousand)}
|
|
408
|
-
belowThousand(rest)
|
|
489
|
+
lakh && `${belowHundred(lakh, w)} ${w.indian.lakh}`,
|
|
490
|
+
thousand && `${belowHundred(thousand, w)} ${w.indian.thousand}`,
|
|
491
|
+
belowThousand(rest, w)
|
|
409
492
|
]);
|
|
410
493
|
}
|
|
411
|
-
function international(digits) {
|
|
494
|
+
function international(digits, w) {
|
|
412
495
|
digits = digits.replace(/^0+/, "");
|
|
413
496
|
if (digits === "") {
|
|
414
497
|
return "";
|
|
415
498
|
}
|
|
416
|
-
const
|
|
499
|
+
const scales = w.international;
|
|
500
|
+
const maxDigits = scales.length * 3;
|
|
417
501
|
if (digits.length > maxDigits) {
|
|
418
|
-
const top = international(digits.slice(0, -(maxDigits - 3)));
|
|
419
|
-
const last =
|
|
420
|
-
return join([top && `${top} ${last}`, international(digits.slice(-(maxDigits - 3)))]);
|
|
502
|
+
const top = international(digits.slice(0, -(maxDigits - 3)), w);
|
|
503
|
+
const last = scales[scales.length - 1];
|
|
504
|
+
return join([top && `${top} ${last}`, international(digits.slice(-(maxDigits - 3)), w)]);
|
|
421
505
|
}
|
|
422
506
|
const parts = [];
|
|
423
507
|
for (let end = digits.length, scale = 0; end > 0; end -= 3, scale++) {
|
|
424
508
|
const group = Number(digits.slice(Math.max(0, end - 3), end));
|
|
425
509
|
if (group) {
|
|
426
|
-
parts.unshift(join([belowThousand(group),
|
|
510
|
+
parts.unshift(join([belowThousand(group, w), scales[scale]]));
|
|
427
511
|
}
|
|
428
512
|
}
|
|
429
513
|
return join(parts);
|
|
430
514
|
}
|
|
431
|
-
function amountInWords(value, { system = "indian" } = {}) {
|
|
515
|
+
function amountInWords(value, { system = "indian", words } = {}) {
|
|
432
516
|
if (system !== "indian" && system !== "international") {
|
|
433
517
|
throw new RangeError(`system must be "indian" or "international", got "${system}".`);
|
|
434
518
|
}
|
|
519
|
+
const w = readWords(words);
|
|
435
520
|
let digits;
|
|
436
521
|
let negative = false;
|
|
437
522
|
if (typeof value === "number") {
|
|
@@ -451,14 +536,14 @@ var FinancialCalculators = (() => {
|
|
|
451
536
|
} else {
|
|
452
537
|
throw new TypeError(`value must be a number, a BigInt or a string of digits, got ${String(value)}.`);
|
|
453
538
|
}
|
|
454
|
-
const
|
|
455
|
-
if (
|
|
456
|
-
return
|
|
539
|
+
const text = system === "indian" ? indian(digits, w) : international(digits, w);
|
|
540
|
+
if (text === "") {
|
|
541
|
+
return w.zero;
|
|
457
542
|
}
|
|
458
|
-
return negative ?
|
|
543
|
+
return negative ? join([w.minus, text]) : text;
|
|
459
544
|
}
|
|
460
545
|
|
|
461
546
|
// src/index.js
|
|
462
|
-
var VERSION = true ? "1.0
|
|
547
|
+
var VERSION = true ? "1.1.0" : "development";
|
|
463
548
|
return __toCommonJS(index_exports);
|
|
464
549
|
})();
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! financial-calculators 1.0
|
|
2
|
-
"use strict";var FinancialCalculators=(()=>{var P=Object.defineProperty;var
|
|
1
|
+
/*! financial-calculators 1.1.0 | GPL-3.0-or-later | https://wpgenius.github.io/financial-calculators-js/ */
|
|
2
|
+
"use strict";var FinancialCalculators=(()=>{var P=Object.defineProperty;var X=Object.getOwnPropertyDescriptor;var nn=Object.getOwnPropertyNames;var tn=Object.prototype.hasOwnProperty;var en=(n,t)=>{for(var o in t)P(n,o,{get:t[o],enumerable:!0})},rn=(n,t,o,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of nn(t))!tn.call(n,i)&&i!==o&&P(n,i,{get:()=>t[i],enumerable:!(e=X(t,i))||e.enumerable});return n};var on=n=>rn(P({},"__esModule",{value:!0}),n);var pn={};en(pn,{VERSION:()=>dn,amountInWords:()=>J,calculate:()=>L,emi:()=>O,formatCompact:()=>Z,formatCurrency:()=>Q,formatNumber:()=>T,goal:()=>C,groupDigits:()=>B,lumpsum:()=>F,register:()=>U,sip:()=>I,swp:()=>R,types:()=>D});function l(n,t,o=0){let e=typeof t=="string"&&t.trim()!==""?Number(t):t;if(typeof e!="number"||!Number.isFinite(e))throw new TypeError(`${n} must be a finite number, got ${String(t)}.`);if(e<o)throw new RangeError(`${n} must be at least ${o}, got ${e}.`);return e}function y(n){let t=Math.round(l("years",n)*12);if(t<1)throw new RangeError(`years must be at least one month (1/12), got ${n}.`);return t}function w(n){if(n==null||n==="")return;let t=l("startYear",n,-1e6);if(!Number.isInteger(t))throw new RangeError(`startYear must be a whole year, got ${n}.`);return t}function $(n,t,o){let e=r=>{let a=r/12;return{...o===void 0?{year:a,month:r}:{year:a,month:r,calendarYear:o+a},...t(r)}},i=[];for(let r=0;r<n;r+=12)i.push(e(r));return i.push(e(n)),i}function N(n,t,o){return t===0?n*o:n*((Math.pow(1+t,o)-1)/t)*(1+t)}function I({monthlyAmount:n,annualRate:t,years:o,startYear:e}){let i=l("monthlyAmount",n),r=l("annualRate",t)/100/12,a=y(o),s=w(e),d=N(i,r,a),m=i*a;return{invested:m,returns:d-m,total:d,months:a,series:$(a,c=>({invested:i*c,total:N(i,r,c)}),s)}}function F({amount:n,annualRate:t,years:o,compoundingPerYear:e=1,startYear:i}){let r=l("amount",n),a=l("annualRate",t)/100,s=y(o),d=w(i),m=l("compoundingPerYear",e,1),c=f=>r*Math.pow(1+a/m,m*f/12),p=c(s);return{invested:r,returns:p-r,total:p,months:s,series:$(s,f=>({invested:r,total:c(f)}),d)}}function R({investment:n,monthlyWithdrawal:t,annualRate:o,years:e,startYear:i}){let r=l("investment",n),a=l("monthlyWithdrawal",t),s=l("annualRate",o)/100/12,d=y(e),m=w(i),c=[r],p=[0],f=r,b=0,g=null;for(let u=1;u<=d;u++){let h=Math.min(a,f);f-=h,b+=h,f<=0?(f=0,g===null&&a>0&&(g=u)):f+=f*s,c.push(f),p.push(b)}return{investment:r,totalWithdrawn:b,finalBalance:f,returns:f+b-r,depletedMonth:g,months:d,series:$(d,u=>({balance:c[u],withdrawn:p[u]}),m)}}function C({presentCost:n,currentSavings:t=0,inflationRate:o,annualRate:e,years:i,startYear:r}){let a=l("presentCost",n),s=l("currentSavings",t),d=l("inflationRate",o)/100,m=l("annualRate",e)/100,c=y(i),p=w(r),f=m/12,b=x=>a*Math.pow(1+d,x/12),g=x=>s*Math.pow(1+m,x/12),u=b(c),h=g(c),E=Math.max(0,u-h),j=E/N(1,f,c);return{presentCost:a,futureCost:u,savingsFutureValue:h,shortfall:E,monthlyInvestment:j,totalInvested:j*c,months:c,...p===void 0?{}:{targetYear:p+c/12},series:$(c,x=>{let z=N(j,f,x);return{goalCost:b(x),savings:g(x),investments:z,total:g(x)+z}},p)}}function O({principal:n,annualRate:t,years:o,startYear:e}){let i=l("principal",n),r=l("annualRate",t)/100/12,a=y(o),s=w(e),d=r===0?i/a:i*r*Math.pow(1+r,a)/(Math.pow(1+r,a)-1),m=[i],c=[0],p=[0],f=i;for(let u=1;u<=a;u++){let h=f*r,E=u===a?f:d-h;f=Math.max(0,f-E),m.push(f),c.push(c[u-1]+E),p.push(p[u-1]+h)}let b=[];for(let u=0;u<a;u+=12){let h=Math.min(u+12,a);b.push({year:b.length+1,principalPaid:c[h]-c[u],interestPaid:p[h]-p[u],balance:m[h]})}let g=d*a;return{emi:d,principal:i,totalInterest:g-i,totalPayment:g,months:a,schedule:b,series:$(a,u=>({balance:m[u],principalPaid:c[u],interestPaid:p[u]}),s)}}var k={sip:I,lumpsum:F,swp:R,goal:C,emi:O};function D(){return Object.keys(k)}function L(n,t){if(!Object.prototype.hasOwnProperty.call(k,n))throw new Error(`Unknown calculator "${n}". Available: ${D().join(", ")}.`);return k[n](t)}function U(n,t){if(typeof n!="string"||n===""||typeof t!="function")throw new TypeError("register( type, fn ) needs a type name and a function.");k[n]=t}var G={indian:"en-IN",international:"en-US"},v=!1,_=!1,H=new Map;function an(n,t){let o=n+":"+t,e=H.get(o);return e||(e=new Intl.NumberFormat(G[n],{minimumFractionDigits:t,maximumFractionDigits:t,useGrouping:!0}),H.set(o,e)),e}function sn(){if(!v){v=!0;try{_=new Intl.NumberFormat("en-IN").format(1234567)==="12,34,567"&&new Intl.NumberFormat("en-US").format(1234567)==="1,234,567"}catch{_=!1}}return _}function A(n){if(!Object.prototype.hasOwnProperty.call(G,n))throw new RangeError(`system must be "indian" or "international", got "${n}".`);return n}function K(n){if(!Number.isInteger(n)||n<0||n>20)throw new RangeError(`decimals must be a whole number from 0 to 20, got ${n}.`);return n}function B(n,t="indian"){if(n.length<=3)return n;let o=n.slice(-3),e=n.slice(0,-3),i=A(t)==="indian"?2:3,r=new RegExp(`\\B(?=(\\d{${i}})+(?!\\d))`,"g");return e.replace(r,",")+","+o}function un(n,t,o){let e=Math.abs(n).toFixed(t),[i,r]=e.split(".");return(n<0&&Number(e)!==0?"-":"")+B(i,o)+(r?"."+r:"")}function T(n,{system:t="indian",decimals:o=0}={}){if(A(t),K(o),typeof n!="number"||!Number.isFinite(n))throw new TypeError(`value must be a finite number, got ${String(n)}.`);let i=Number(n.toFixed(o))===0?0:n;return sn()?an(t,o).format(i):un(i,o,t)}function Q(n,{symbol:t="\u20B9",position:o="before",system:e="indian",decimals:i=0}={}){let r=T(n,{system:e,decimals:i}),a=r.startsWith("-"),s=a?r.slice(1):r,d=a?"-":"";return o==="after"?`${d}${s} ${t}`:`${d}${t}${s}`}var cn={indian:[[1e7,"Cr"],[1e5,"L"],[1e3,"K"]],international:[[1e12,"T"],[1e9,"B"],[1e6,"M"],[1e3,"K"]]};function Z(n,{system:t="indian",decimals:o=1}={}){if(A(t),K(o),typeof n!="number"||!Number.isFinite(n))throw new TypeError(`value must be a finite number, got ${String(n)}.`);let e=Math.abs(n),i=n<0?"-":"";for(let[r,a]of cn[t])if(e>=r){let s=Number((e/r).toFixed(o));return`${i}${T(s,{system:t,decimals:s%1===0?0:o})}${a}`}return T(n,{system:t,decimals:0})}var M={ones:["","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"],tens:["","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"],hundred:"Hundred",and:"and",zero:"Zero",minus:"Minus",indian:{thousand:"Thousand",lakh:"Lakh",crore:"Crore"},international:["","Thousand","Million","Billion","Trillion","Quadrillion","Quintillion","Sextillion","Septillion","Octillion","Nonillion","Decillion"]},fn=["hundred","and","zero","minus"];function ln(n){if(n===void 0)return M;if(!n||typeof n!="object")throw new TypeError("words must be an object.");let t=(e,i)=>{if(n[e]===void 0)return M[e];let r=n[e];if(!Array.isArray(r)||r.length!==i||!r.every(a=>typeof a=="string"))throw new TypeError(`words.${e} must be an array of ${i} strings.`);return r},o={ones:t("ones",20),tens:t("tens",10),international:t("international",M.international.length),indian:{...M.indian}};for(let e of fn){if(n[e]!==void 0&&typeof n[e]!="string")throw new TypeError(`words.${e} must be a string.`);o[e]=n[e]??M[e]}if(n.indian!==void 0){if(!n.indian||typeof n.indian!="object")throw new TypeError("words.indian must be an object with thousand, lakh and crore.");for(let e of Object.keys(M.indian))if(n.indian[e]!==void 0){if(typeof n.indian[e]!="string")throw new TypeError(`words.indian.${e} must be a string.`);o.indian[e]=n.indian[e]}}return o}function S(n){return n.filter(Boolean).join(" ")}function Y(n,t){return n<20?t.ones[n]:S([t.tens[Math.floor(n/10)],t.ones[n%10]])}function q(n,t){let o=Math.floor(n/100),e=n%100;return o?S([t.ones[o],t.hundred,e?t.and:"",e?Y(e,t):""]):Y(e,t)}function W(n,t){if(n=n.replace(/^0+/,""),n==="")return"";if(n.length>7){let a=W(n.slice(0,-7),t);return S([a&&`${a} ${t.indian.crore}`,W(n.slice(-7),t)])}let o=Number(n),e=Math.floor(o/1e5),i=Math.floor(o%1e5/1e3),r=o%1e3;return S([e&&`${Y(e,t)} ${t.indian.lakh}`,i&&`${Y(i,t)} ${t.indian.thousand}`,q(r,t)])}function V(n,t){if(n=n.replace(/^0+/,""),n==="")return"";let o=t.international,e=o.length*3;if(n.length>e){let r=V(n.slice(0,-(e-3)),t),a=o[o.length-1];return S([r&&`${r} ${a}`,V(n.slice(-(e-3)),t)])}let i=[];for(let r=n.length,a=0;r>0;r-=3,a++){let s=Number(n.slice(Math.max(0,r-3),r));s&&i.unshift(S([q(s,t),o[a]]))}return S(i)}function J(n,{system:t="indian",words:o}={}){if(t!=="indian"&&t!=="international")throw new RangeError(`system must be "indian" or "international", got "${t}".`);let e=ln(o),i,r=!1;if(typeof n=="number"){if(!Number.isFinite(n))throw new TypeError(`value must be a finite number, got ${n}.`);let s=Math.round(Math.abs(n));r=n<0&&s!==0,i=BigInt(s).toString()}else if(typeof n=="bigint")r=n<0n,i=(r?-n:n).toString();else if(typeof n=="string"&&/^-?\d+$/.test(n.trim())){let s=n.trim();r=s.startsWith("-")&&/[1-9]/.test(s),i=s.replace("-","")}else throw new TypeError(`value must be a number, a BigInt or a string of digits, got ${String(n)}.`);let a=t==="indian"?W(i,e):V(i,e);return a===""?e.zero:r?S([e.minus,a]):a}var dn="1.1.0";return on(pn);})();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wpgenius/financial-calculators",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "Financial calculators in plain JavaScript with no dependencies: SIP, lump sum, SWP, goal and EMI, Indian and international number formatting, and amounts in words.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"finance",
|
package/src/calculators/emi.js
CHANGED
|
@@ -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
|
* Loan EMI (equated monthly instalment), interest reducing monthly, with a
|
|
@@ -8,6 +8,7 @@ import { readNumber, toMonths, yearlySeries } from '../utils.js';
|
|
|
8
8
|
* @param {number} inputs.principal Loan amount.
|
|
9
9
|
* @param {number} inputs.annualRate Interest, % a year.
|
|
10
10
|
* @param {number} inputs.years Tenure in years (fractions allowed).
|
|
11
|
+
* @param {number} [inputs.startYear] Optional calendar year of the start; series points get calendarYear.
|
|
11
12
|
* @return {{emi: number, principal: number, totalInterest: number,
|
|
12
13
|
* totalPayment: number, months: number,
|
|
13
14
|
* schedule: Array<{year: number, principalPaid: number, interestPaid: number, balance: number}>,
|
|
@@ -15,10 +16,11 @@ import { readNumber, toMonths, yearlySeries } from '../utils.js';
|
|
|
15
16
|
* schedule: one row per loan year (the last may be shorter) with what
|
|
16
17
|
* that year paid; series: cumulative totals for charts.
|
|
17
18
|
*/
|
|
18
|
-
export function emi( { principal, annualRate, years } ) {
|
|
19
|
+
export function emi( { principal, annualRate, years, startYear } ) {
|
|
19
20
|
const loan = readNumber( 'principal', principal );
|
|
20
21
|
const i = readNumber( 'annualRate', annualRate ) / 100 / 12;
|
|
21
22
|
const months = toMonths( years );
|
|
23
|
+
const firstYear = readStartYear( startYear );
|
|
22
24
|
|
|
23
25
|
const instalment = i === 0
|
|
24
26
|
? loan / months
|
|
@@ -60,6 +62,6 @@ export function emi( { principal, annualRate, years } ) {
|
|
|
60
62
|
balance: balances[ month ],
|
|
61
63
|
principalPaid: principalPaid[ month ],
|
|
62
64
|
interestPaid: interestPaid[ month ],
|
|
63
|
-
} ) ),
|
|
65
|
+
} ), firstYear ),
|
|
64
66
|
};
|
|
65
67
|
}
|
package/src/calculators/goal.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { readNumber, toMonths, yearlySeries, annuityDueValue } from '../utils.js';
|
|
1
|
+
import { readNumber, readStartYear, toMonths, yearlySeries, annuityDueValue } from '../utils.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Time-based goal: what a goal will cost after inflation, and the monthly
|
|
@@ -12,18 +12,20 @@ import { readNumber, toMonths, yearlySeries, annuityDueValue } from '../utils.js
|
|
|
12
12
|
* @param {number} inputs.inflationRate Inflation, % a year.
|
|
13
13
|
* @param {number} inputs.annualRate Expected return, % a year.
|
|
14
14
|
* @param {number} inputs.years Years until the goal (fractions allowed).
|
|
15
|
+
* @param {number} [inputs.startYear] Optional calendar year of the start; series points get calendarYear.
|
|
15
16
|
* @return {{presentCost: number, futureCost: number, savingsFutureValue: number,
|
|
16
17
|
* shortfall: number, monthlyInvestment: number, totalInvested: number,
|
|
17
|
-
* months: number,
|
|
18
|
+
* months: number, targetYear?: number (with startYear),
|
|
18
19
|
* series: Array<{year: number, month: number, goalCost: number,
|
|
19
20
|
* savings: number, investments: number, total: number}>}}
|
|
20
21
|
*/
|
|
21
|
-
export function goal( { presentCost, currentSavings = 0, inflationRate, annualRate, years } ) {
|
|
22
|
+
export function goal( { presentCost, currentSavings = 0, inflationRate, annualRate, years, startYear } ) {
|
|
22
23
|
const cost = readNumber( 'presentCost', presentCost );
|
|
23
24
|
const savings = readNumber( 'currentSavings', currentSavings );
|
|
24
25
|
const inflation = readNumber( 'inflationRate', inflationRate ) / 100;
|
|
25
26
|
const rate = readNumber( 'annualRate', annualRate ) / 100;
|
|
26
27
|
const months = toMonths( years );
|
|
28
|
+
const firstYear = readStartYear( startYear );
|
|
27
29
|
const i = rate / 12;
|
|
28
30
|
|
|
29
31
|
const costAt = ( month ) => cost * Math.pow( 1 + inflation, month / 12 );
|
|
@@ -42,6 +44,7 @@ export function goal( { presentCost, currentSavings = 0, inflationRate, annualRa
|
|
|
42
44
|
monthlyInvestment,
|
|
43
45
|
totalInvested: monthlyInvestment * months,
|
|
44
46
|
months,
|
|
47
|
+
...( firstYear === undefined ? {} : { targetYear: firstYear + months / 12 } ),
|
|
45
48
|
series: yearlySeries( months, ( month ) => {
|
|
46
49
|
const investments = annuityDueValue( monthlyInvestment, i, month );
|
|
47
50
|
return {
|
|
@@ -50,6 +53,6 @@ export function goal( { presentCost, currentSavings = 0, inflationRate, annualRa
|
|
|
50
53
|
investments,
|
|
51
54
|
total: savingsAt( month ) + investments,
|
|
52
55
|
};
|
|
53
|
-
} ),
|
|
56
|
+
}, firstYear ),
|
|
54
57
|
};
|
|
55
58
|
}
|
|
@@ -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
|
* Lump sum (one-time investment), compounded a given number of times a year.
|
|
@@ -7,14 +7,16 @@ import { readNumber, toMonths, yearlySeries } from '../utils.js';
|
|
|
7
7
|
* @param {number} inputs.amount Amount invested once, at the start.
|
|
8
8
|
* @param {number} inputs.annualRate Expected return, % a year.
|
|
9
9
|
* @param {number} inputs.years Duration in years (fractions allowed).
|
|
10
|
+
* @param {number} [inputs.startYear] Optional calendar year of the start; series points get calendarYear.
|
|
10
11
|
* @param {number} [inputs.compoundingPerYear=1] 1 yearly, 4 quarterly, 12 monthly.
|
|
11
12
|
* @return {{invested: number, returns: number, total: number, months: number,
|
|
12
13
|
* series: Array<{year: number, month: number, invested: number, total: number}>}}
|
|
13
14
|
*/
|
|
14
|
-
export function lumpsum( { amount, annualRate, years, compoundingPerYear = 1 } ) {
|
|
15
|
+
export function lumpsum( { amount, annualRate, years, compoundingPerYear = 1, startYear } ) {
|
|
15
16
|
const invested = readNumber( 'amount', amount );
|
|
16
17
|
const rate = readNumber( 'annualRate', annualRate ) / 100;
|
|
17
18
|
const months = toMonths( years );
|
|
19
|
+
const firstYear = readStartYear( startYear );
|
|
18
20
|
const k = readNumber( 'compoundingPerYear', compoundingPerYear, 1 );
|
|
19
21
|
|
|
20
22
|
const valueAt = ( month ) => invested * Math.pow( 1 + rate / k, ( k * month ) / 12 );
|
|
@@ -28,6 +30,6 @@ export function lumpsum( { amount, annualRate, years, compoundingPerYear = 1 } )
|
|
|
28
30
|
series: yearlySeries( months, ( month ) => ( {
|
|
29
31
|
invested,
|
|
30
32
|
total: valueAt( month ),
|
|
31
|
-
} ) ),
|
|
33
|
+
} ), firstYear ),
|
|
32
34
|
};
|
|
33
35
|
}
|
package/src/calculators/sip.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { readNumber, toMonths, yearlySeries, annuityDueValue } from '../utils.js';
|
|
1
|
+
import { readNumber, readStartYear, toMonths, yearlySeries, annuityDueValue } from '../utils.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* SIP (systematic investment plan): the same amount invested at the start of
|
|
@@ -8,13 +8,15 @@ import { readNumber, toMonths, yearlySeries, annuityDueValue } from '../utils.js
|
|
|
8
8
|
* @param {number} inputs.monthlyAmount Amount invested each month.
|
|
9
9
|
* @param {number} inputs.annualRate Expected return, % a year (12 for 12%).
|
|
10
10
|
* @param {number} inputs.years Duration in years (fractions allowed).
|
|
11
|
+
* @param {number} [inputs.startYear] Optional calendar year of the start; series points get calendarYear.
|
|
11
12
|
* @return {{invested: number, returns: number, total: number, months: number,
|
|
12
13
|
* series: Array<{year: number, month: number, invested: number, total: number}>}}
|
|
13
14
|
*/
|
|
14
|
-
export function sip( { monthlyAmount, annualRate, years } ) {
|
|
15
|
+
export function sip( { monthlyAmount, annualRate, years, startYear } ) {
|
|
15
16
|
const amount = readNumber( 'monthlyAmount', monthlyAmount );
|
|
16
17
|
const i = readNumber( 'annualRate', annualRate ) / 100 / 12;
|
|
17
18
|
const months = toMonths( years );
|
|
19
|
+
const firstYear = readStartYear( startYear );
|
|
18
20
|
|
|
19
21
|
const total = annuityDueValue( amount, i, months );
|
|
20
22
|
const invested = amount * months;
|
|
@@ -27,6 +29,6 @@ export function sip( { monthlyAmount, annualRate, years } ) {
|
|
|
27
29
|
series: yearlySeries( months, ( month ) => ( {
|
|
28
30
|
invested: amount * month,
|
|
29
31
|
total: annuityDueValue( amount, i, month ),
|
|
30
|
-
} ) ),
|
|
32
|
+
} ), firstYear ),
|
|
31
33
|
};
|
|
32
34
|
}
|