@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 +17 -3
- package/dist/financial-calculators.esm.js +168 -83
- package/dist/financial-calculators.js +169 -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,5 @@
|
|
|
1
|
-
/*! financial-calculators 1.
|
|
1
|
+
/*! financial-calculators 1.1.0 | GPL-3.0-or-later | https://wpgenius.github.io/financial-calculators-js/ */
|
|
2
|
+
"use strict";
|
|
2
3
|
var FinancialCalculators = (() => {
|
|
3
4
|
var __defProp = Object.defineProperty;
|
|
4
5
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
@@ -55,12 +56,27 @@ var FinancialCalculators = (() => {
|
|
|
55
56
|
}
|
|
56
57
|
return months;
|
|
57
58
|
}
|
|
58
|
-
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
|
+
};
|
|
59
75
|
const series = [];
|
|
60
76
|
for (let month = 0; month < months; month += 12) {
|
|
61
|
-
series.push(
|
|
77
|
+
series.push(at(month));
|
|
62
78
|
}
|
|
63
|
-
series.push(
|
|
79
|
+
series.push(at(months));
|
|
64
80
|
return series;
|
|
65
81
|
}
|
|
66
82
|
function annuityDueValue(amount, i, n) {
|
|
@@ -71,10 +87,11 @@ var FinancialCalculators = (() => {
|
|
|
71
87
|
}
|
|
72
88
|
|
|
73
89
|
// src/calculators/sip.js
|
|
74
|
-
function sip({ monthlyAmount, annualRate, years }) {
|
|
90
|
+
function sip({ monthlyAmount, annualRate, years, startYear }) {
|
|
75
91
|
const amount = readNumber("monthlyAmount", monthlyAmount);
|
|
76
92
|
const i = readNumber("annualRate", annualRate) / 100 / 12;
|
|
77
93
|
const months = toMonths(years);
|
|
94
|
+
const firstYear = readStartYear(startYear);
|
|
78
95
|
const total = annuityDueValue(amount, i, months);
|
|
79
96
|
const invested = amount * months;
|
|
80
97
|
return {
|
|
@@ -85,15 +102,16 @@ var FinancialCalculators = (() => {
|
|
|
85
102
|
series: yearlySeries(months, (month) => ({
|
|
86
103
|
invested: amount * month,
|
|
87
104
|
total: annuityDueValue(amount, i, month)
|
|
88
|
-
}))
|
|
105
|
+
}), firstYear)
|
|
89
106
|
};
|
|
90
107
|
}
|
|
91
108
|
|
|
92
109
|
// src/calculators/lumpsum.js
|
|
93
|
-
function lumpsum({ amount, annualRate, years, compoundingPerYear = 1 }) {
|
|
110
|
+
function lumpsum({ amount, annualRate, years, compoundingPerYear = 1, startYear }) {
|
|
94
111
|
const invested = readNumber("amount", amount);
|
|
95
112
|
const rate = readNumber("annualRate", annualRate) / 100;
|
|
96
113
|
const months = toMonths(years);
|
|
114
|
+
const firstYear = readStartYear(startYear);
|
|
97
115
|
const k = readNumber("compoundingPerYear", compoundingPerYear, 1);
|
|
98
116
|
const valueAt = (month) => invested * Math.pow(1 + rate / k, k * month / 12);
|
|
99
117
|
const total = valueAt(months);
|
|
@@ -105,16 +123,17 @@ var FinancialCalculators = (() => {
|
|
|
105
123
|
series: yearlySeries(months, (month) => ({
|
|
106
124
|
invested,
|
|
107
125
|
total: valueAt(month)
|
|
108
|
-
}))
|
|
126
|
+
}), firstYear)
|
|
109
127
|
};
|
|
110
128
|
}
|
|
111
129
|
|
|
112
130
|
// src/calculators/swp.js
|
|
113
|
-
function swp({ investment, monthlyWithdrawal, annualRate, years }) {
|
|
131
|
+
function swp({ investment, monthlyWithdrawal, annualRate, years, startYear }) {
|
|
114
132
|
const start = readNumber("investment", investment);
|
|
115
133
|
const withdrawal = readNumber("monthlyWithdrawal", monthlyWithdrawal);
|
|
116
134
|
const i = readNumber("annualRate", annualRate) / 100 / 12;
|
|
117
135
|
const months = toMonths(years);
|
|
136
|
+
const firstYear = readStartYear(startYear);
|
|
118
137
|
const balances = [start];
|
|
119
138
|
const withdrawnTotals = [0];
|
|
120
139
|
let balance = start;
|
|
@@ -145,17 +164,18 @@ var FinancialCalculators = (() => {
|
|
|
145
164
|
series: yearlySeries(months, (month) => ({
|
|
146
165
|
balance: balances[month],
|
|
147
166
|
withdrawn: withdrawnTotals[month]
|
|
148
|
-
}))
|
|
167
|
+
}), firstYear)
|
|
149
168
|
};
|
|
150
169
|
}
|
|
151
170
|
|
|
152
171
|
// src/calculators/goal.js
|
|
153
|
-
function goal({ presentCost, currentSavings = 0, inflationRate, annualRate, years }) {
|
|
172
|
+
function goal({ presentCost, currentSavings = 0, inflationRate, annualRate, years, startYear }) {
|
|
154
173
|
const cost = readNumber("presentCost", presentCost);
|
|
155
174
|
const savings = readNumber("currentSavings", currentSavings);
|
|
156
175
|
const inflation = readNumber("inflationRate", inflationRate) / 100;
|
|
157
176
|
const rate = readNumber("annualRate", annualRate) / 100;
|
|
158
177
|
const months = toMonths(years);
|
|
178
|
+
const firstYear = readStartYear(startYear);
|
|
159
179
|
const i = rate / 12;
|
|
160
180
|
const costAt = (month) => cost * Math.pow(1 + inflation, month / 12);
|
|
161
181
|
const savingsAt = (month) => savings * Math.pow(1 + rate, month / 12);
|
|
@@ -171,6 +191,7 @@ var FinancialCalculators = (() => {
|
|
|
171
191
|
monthlyInvestment,
|
|
172
192
|
totalInvested: monthlyInvestment * months,
|
|
173
193
|
months,
|
|
194
|
+
...firstYear === void 0 ? {} : { targetYear: firstYear + months / 12 },
|
|
174
195
|
series: yearlySeries(months, (month) => {
|
|
175
196
|
const investments = annuityDueValue(monthlyInvestment, i, month);
|
|
176
197
|
return {
|
|
@@ -179,15 +200,16 @@ var FinancialCalculators = (() => {
|
|
|
179
200
|
investments,
|
|
180
201
|
total: savingsAt(month) + investments
|
|
181
202
|
};
|
|
182
|
-
})
|
|
203
|
+
}, firstYear)
|
|
183
204
|
};
|
|
184
205
|
}
|
|
185
206
|
|
|
186
207
|
// src/calculators/emi.js
|
|
187
|
-
function emi({ principal, annualRate, years }) {
|
|
208
|
+
function emi({ principal, annualRate, years, startYear }) {
|
|
188
209
|
const loan = readNumber("principal", principal);
|
|
189
210
|
const i = readNumber("annualRate", annualRate) / 100 / 12;
|
|
190
211
|
const months = toMonths(years);
|
|
212
|
+
const firstYear = readStartYear(startYear);
|
|
191
213
|
const instalment = i === 0 ? loan / months : loan * i * Math.pow(1 + i, months) / (Math.pow(1 + i, months) - 1);
|
|
192
214
|
const balances = [loan];
|
|
193
215
|
const principalPaid = [0];
|
|
@@ -223,7 +245,7 @@ var FinancialCalculators = (() => {
|
|
|
223
245
|
balance: balances[month],
|
|
224
246
|
principalPaid: principalPaid[month],
|
|
225
247
|
interestPaid: interestPaid[month]
|
|
226
|
-
}))
|
|
248
|
+
}), firstYear)
|
|
227
249
|
};
|
|
228
250
|
}
|
|
229
251
|
|
|
@@ -249,6 +271,20 @@ var FinancialCalculators = (() => {
|
|
|
249
271
|
var LOCALES = { indian: "en-IN", international: "en-US" };
|
|
250
272
|
var intlChecked = false;
|
|
251
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
|
+
}
|
|
252
288
|
function canUseIntl() {
|
|
253
289
|
if (!intlChecked) {
|
|
254
290
|
intlChecked = true;
|
|
@@ -297,11 +333,7 @@ var FinancialCalculators = (() => {
|
|
|
297
333
|
const rounded = Number(value.toFixed(decimals));
|
|
298
334
|
const number = rounded === 0 ? 0 : value;
|
|
299
335
|
if (canUseIntl()) {
|
|
300
|
-
return
|
|
301
|
-
minimumFractionDigits: decimals,
|
|
302
|
-
maximumFractionDigits: decimals,
|
|
303
|
-
useGrouping: true
|
|
304
|
-
}).format(number);
|
|
336
|
+
return formatter(system, decimals).format(number);
|
|
305
337
|
}
|
|
306
338
|
return formatByHand(number, decimals, system);
|
|
307
339
|
}
|
|
@@ -334,103 +366,157 @@ var FinancialCalculators = (() => {
|
|
|
334
366
|
}
|
|
335
367
|
|
|
336
368
|
// src/format/words.js
|
|
337
|
-
var
|
|
338
|
-
|
|
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
|
-
|
|
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) {
|
|
375
462
|
if (n < 20) {
|
|
376
|
-
return
|
|
463
|
+
return w.ones[n];
|
|
377
464
|
}
|
|
378
|
-
return [
|
|
465
|
+
return join([w.tens[Math.floor(n / 10)], w.ones[n % 10]]);
|
|
379
466
|
}
|
|
380
|
-
function belowThousand(n) {
|
|
467
|
+
function belowThousand(n, w) {
|
|
381
468
|
const hundreds = Math.floor(n / 100);
|
|
382
469
|
const rest = n % 100;
|
|
383
470
|
if (!hundreds) {
|
|
384
|
-
return belowHundred(rest);
|
|
471
|
+
return belowHundred(rest, w);
|
|
385
472
|
}
|
|
386
|
-
return
|
|
387
|
-
}
|
|
388
|
-
function join(parts) {
|
|
389
|
-
return parts.filter(Boolean).join(" ");
|
|
473
|
+
return join([w.ones[hundreds], w.hundred, rest ? w.and : "", rest ? belowHundred(rest, w) : ""]);
|
|
390
474
|
}
|
|
391
|
-
function indian(digits) {
|
|
475
|
+
function indian(digits, w) {
|
|
392
476
|
digits = digits.replace(/^0+/, "");
|
|
393
477
|
if (digits === "") {
|
|
394
478
|
return "";
|
|
395
479
|
}
|
|
396
480
|
if (digits.length > 7) {
|
|
397
|
-
const crores = indian(digits.slice(0, -7));
|
|
398
|
-
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)]);
|
|
399
483
|
}
|
|
400
484
|
const n = Number(digits);
|
|
401
485
|
const lakh = Math.floor(n / 1e5);
|
|
402
486
|
const thousand = Math.floor(n % 1e5 / 1e3);
|
|
403
487
|
const rest = n % 1e3;
|
|
404
488
|
return join([
|
|
405
|
-
lakh && `${belowHundred(lakh)}
|
|
406
|
-
thousand && `${belowHundred(thousand)}
|
|
407
|
-
belowThousand(rest)
|
|
489
|
+
lakh && `${belowHundred(lakh, w)} ${w.indian.lakh}`,
|
|
490
|
+
thousand && `${belowHundred(thousand, w)} ${w.indian.thousand}`,
|
|
491
|
+
belowThousand(rest, w)
|
|
408
492
|
]);
|
|
409
493
|
}
|
|
410
|
-
function international(digits) {
|
|
494
|
+
function international(digits, w) {
|
|
411
495
|
digits = digits.replace(/^0+/, "");
|
|
412
496
|
if (digits === "") {
|
|
413
497
|
return "";
|
|
414
498
|
}
|
|
415
|
-
const
|
|
499
|
+
const scales = w.international;
|
|
500
|
+
const maxDigits = scales.length * 3;
|
|
416
501
|
if (digits.length > maxDigits) {
|
|
417
|
-
const top = international(digits.slice(0, -(maxDigits - 3)));
|
|
418
|
-
const last =
|
|
419
|
-
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)]);
|
|
420
505
|
}
|
|
421
506
|
const parts = [];
|
|
422
507
|
for (let end = digits.length, scale = 0; end > 0; end -= 3, scale++) {
|
|
423
508
|
const group = Number(digits.slice(Math.max(0, end - 3), end));
|
|
424
509
|
if (group) {
|
|
425
|
-
parts.unshift(join([belowThousand(group),
|
|
510
|
+
parts.unshift(join([belowThousand(group, w), scales[scale]]));
|
|
426
511
|
}
|
|
427
512
|
}
|
|
428
513
|
return join(parts);
|
|
429
514
|
}
|
|
430
|
-
function amountInWords(value, { system = "indian" } = {}) {
|
|
515
|
+
function amountInWords(value, { system = "indian", words } = {}) {
|
|
431
516
|
if (system !== "indian" && system !== "international") {
|
|
432
517
|
throw new RangeError(`system must be "indian" or "international", got "${system}".`);
|
|
433
518
|
}
|
|
519
|
+
const w = readWords(words);
|
|
434
520
|
let digits;
|
|
435
521
|
let negative = false;
|
|
436
522
|
if (typeof value === "number") {
|
|
@@ -450,14 +536,14 @@ var FinancialCalculators = (() => {
|
|
|
450
536
|
} else {
|
|
451
537
|
throw new TypeError(`value must be a number, a BigInt or a string of digits, got ${String(value)}.`);
|
|
452
538
|
}
|
|
453
|
-
const
|
|
454
|
-
if (
|
|
455
|
-
return
|
|
539
|
+
const text = system === "indian" ? indian(digits, w) : international(digits, w);
|
|
540
|
+
if (text === "") {
|
|
541
|
+
return w.zero;
|
|
456
542
|
}
|
|
457
|
-
return negative ?
|
|
543
|
+
return negative ? join([w.minus, text]) : text;
|
|
458
544
|
}
|
|
459
545
|
|
|
460
546
|
// src/index.js
|
|
461
|
-
var VERSION = true ? "1.
|
|
547
|
+
var VERSION = true ? "1.1.0" : "development";
|
|
462
548
|
return __toCommonJS(index_exports);
|
|
463
549
|
})();
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! financial-calculators 1.
|
|
2
|
-
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.
|
|
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
|
}
|