@wpgenius/financial-calculators 0.0.0-stage → 1.0.1
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/LICENSE +674 -0
- package/README.md +212 -2
- package/dist/financial-calculators.esm.js +440 -0
- package/dist/financial-calculators.js +464 -0
- package/dist/financial-calculators.min.js +2 -0
- package/package.json +69 -4
- package/src/calculators/emi.js +65 -0
- package/src/calculators/goal.js +55 -0
- package/src/calculators/index.js +51 -0
- package/src/calculators/lumpsum.js +33 -0
- package/src/calculators/sip.js +32 -0
- package/src/calculators/swp.js +60 -0
- package/src/format/number.js +142 -0
- package/src/format/words.js +117 -0
- package/src/index.js +15 -0
- package/src/utils.js +71 -0
- package/types/financial-calculators.d.ts +208 -0
|
@@ -0,0 +1,464 @@
|
|
|
1
|
+
/*! financial-calculators 1.0.1 | GPL-3.0-or-later | https://wpgenius.github.io/financial-calculators-js/ */
|
|
2
|
+
"use strict";
|
|
3
|
+
var FinancialCalculators = (() => {
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
21
|
+
|
|
22
|
+
// src/index.js
|
|
23
|
+
var index_exports = {};
|
|
24
|
+
__export(index_exports, {
|
|
25
|
+
VERSION: () => VERSION,
|
|
26
|
+
amountInWords: () => amountInWords,
|
|
27
|
+
calculate: () => calculate,
|
|
28
|
+
emi: () => emi,
|
|
29
|
+
formatCompact: () => formatCompact,
|
|
30
|
+
formatCurrency: () => formatCurrency,
|
|
31
|
+
formatNumber: () => formatNumber,
|
|
32
|
+
goal: () => goal,
|
|
33
|
+
groupDigits: () => groupDigits,
|
|
34
|
+
lumpsum: () => lumpsum,
|
|
35
|
+
register: () => register,
|
|
36
|
+
sip: () => sip,
|
|
37
|
+
swp: () => swp,
|
|
38
|
+
types: () => types
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
// src/utils.js
|
|
42
|
+
function readNumber(name, value, min = 0) {
|
|
43
|
+
const number = typeof value === "string" && value.trim() !== "" ? Number(value) : value;
|
|
44
|
+
if (typeof number !== "number" || !Number.isFinite(number)) {
|
|
45
|
+
throw new TypeError(`${name} must be a finite number, got ${String(value)}.`);
|
|
46
|
+
}
|
|
47
|
+
if (number < min) {
|
|
48
|
+
throw new RangeError(`${name} must be at least ${min}, got ${number}.`);
|
|
49
|
+
}
|
|
50
|
+
return number;
|
|
51
|
+
}
|
|
52
|
+
function toMonths(years) {
|
|
53
|
+
const months = Math.round(readNumber("years", years) * 12);
|
|
54
|
+
if (months < 1) {
|
|
55
|
+
throw new RangeError(`years must be at least one month (1/12), got ${years}.`);
|
|
56
|
+
}
|
|
57
|
+
return months;
|
|
58
|
+
}
|
|
59
|
+
function yearlySeries(months, point) {
|
|
60
|
+
const series = [];
|
|
61
|
+
for (let month = 0; month < months; month += 12) {
|
|
62
|
+
series.push({ year: month / 12, month, ...point(month) });
|
|
63
|
+
}
|
|
64
|
+
series.push({ year: months / 12, month: months, ...point(months) });
|
|
65
|
+
return series;
|
|
66
|
+
}
|
|
67
|
+
function annuityDueValue(amount, i, n) {
|
|
68
|
+
if (i === 0) {
|
|
69
|
+
return amount * n;
|
|
70
|
+
}
|
|
71
|
+
return amount * ((Math.pow(1 + i, n) - 1) / i) * (1 + i);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// src/calculators/sip.js
|
|
75
|
+
function sip({ monthlyAmount, annualRate, years }) {
|
|
76
|
+
const amount = readNumber("monthlyAmount", monthlyAmount);
|
|
77
|
+
const i = readNumber("annualRate", annualRate) / 100 / 12;
|
|
78
|
+
const months = toMonths(years);
|
|
79
|
+
const total = annuityDueValue(amount, i, months);
|
|
80
|
+
const invested = amount * months;
|
|
81
|
+
return {
|
|
82
|
+
invested,
|
|
83
|
+
returns: total - invested,
|
|
84
|
+
total,
|
|
85
|
+
months,
|
|
86
|
+
series: yearlySeries(months, (month) => ({
|
|
87
|
+
invested: amount * month,
|
|
88
|
+
total: annuityDueValue(amount, i, month)
|
|
89
|
+
}))
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// src/calculators/lumpsum.js
|
|
94
|
+
function lumpsum({ amount, annualRate, years, compoundingPerYear = 1 }) {
|
|
95
|
+
const invested = readNumber("amount", amount);
|
|
96
|
+
const rate = readNumber("annualRate", annualRate) / 100;
|
|
97
|
+
const months = toMonths(years);
|
|
98
|
+
const k = readNumber("compoundingPerYear", compoundingPerYear, 1);
|
|
99
|
+
const valueAt = (month) => invested * Math.pow(1 + rate / k, k * month / 12);
|
|
100
|
+
const total = valueAt(months);
|
|
101
|
+
return {
|
|
102
|
+
invested,
|
|
103
|
+
returns: total - invested,
|
|
104
|
+
total,
|
|
105
|
+
months,
|
|
106
|
+
series: yearlySeries(months, (month) => ({
|
|
107
|
+
invested,
|
|
108
|
+
total: valueAt(month)
|
|
109
|
+
}))
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// src/calculators/swp.js
|
|
114
|
+
function swp({ investment, monthlyWithdrawal, annualRate, years }) {
|
|
115
|
+
const start = readNumber("investment", investment);
|
|
116
|
+
const withdrawal = readNumber("monthlyWithdrawal", monthlyWithdrawal);
|
|
117
|
+
const i = readNumber("annualRate", annualRate) / 100 / 12;
|
|
118
|
+
const months = toMonths(years);
|
|
119
|
+
const balances = [start];
|
|
120
|
+
const withdrawnTotals = [0];
|
|
121
|
+
let balance = start;
|
|
122
|
+
let withdrawn = 0;
|
|
123
|
+
let depletedMonth = null;
|
|
124
|
+
for (let month = 1; month <= months; month++) {
|
|
125
|
+
const take = Math.min(withdrawal, balance);
|
|
126
|
+
balance -= take;
|
|
127
|
+
withdrawn += take;
|
|
128
|
+
if (balance <= 0) {
|
|
129
|
+
balance = 0;
|
|
130
|
+
if (depletedMonth === null && withdrawal > 0) {
|
|
131
|
+
depletedMonth = month;
|
|
132
|
+
}
|
|
133
|
+
} else {
|
|
134
|
+
balance += balance * i;
|
|
135
|
+
}
|
|
136
|
+
balances.push(balance);
|
|
137
|
+
withdrawnTotals.push(withdrawn);
|
|
138
|
+
}
|
|
139
|
+
return {
|
|
140
|
+
investment: start,
|
|
141
|
+
totalWithdrawn: withdrawn,
|
|
142
|
+
finalBalance: balance,
|
|
143
|
+
returns: balance + withdrawn - start,
|
|
144
|
+
depletedMonth,
|
|
145
|
+
months,
|
|
146
|
+
series: yearlySeries(months, (month) => ({
|
|
147
|
+
balance: balances[month],
|
|
148
|
+
withdrawn: withdrawnTotals[month]
|
|
149
|
+
}))
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// src/calculators/goal.js
|
|
154
|
+
function goal({ presentCost, currentSavings = 0, inflationRate, annualRate, years }) {
|
|
155
|
+
const cost = readNumber("presentCost", presentCost);
|
|
156
|
+
const savings = readNumber("currentSavings", currentSavings);
|
|
157
|
+
const inflation = readNumber("inflationRate", inflationRate) / 100;
|
|
158
|
+
const rate = readNumber("annualRate", annualRate) / 100;
|
|
159
|
+
const months = toMonths(years);
|
|
160
|
+
const i = rate / 12;
|
|
161
|
+
const costAt = (month) => cost * Math.pow(1 + inflation, month / 12);
|
|
162
|
+
const savingsAt = (month) => savings * Math.pow(1 + rate, month / 12);
|
|
163
|
+
const futureCost = costAt(months);
|
|
164
|
+
const savingsFutureValue = savingsAt(months);
|
|
165
|
+
const shortfall = Math.max(0, futureCost - savingsFutureValue);
|
|
166
|
+
const monthlyInvestment = shortfall / annuityDueValue(1, i, months);
|
|
167
|
+
return {
|
|
168
|
+
presentCost: cost,
|
|
169
|
+
futureCost,
|
|
170
|
+
savingsFutureValue,
|
|
171
|
+
shortfall,
|
|
172
|
+
monthlyInvestment,
|
|
173
|
+
totalInvested: monthlyInvestment * months,
|
|
174
|
+
months,
|
|
175
|
+
series: yearlySeries(months, (month) => {
|
|
176
|
+
const investments = annuityDueValue(monthlyInvestment, i, month);
|
|
177
|
+
return {
|
|
178
|
+
goalCost: costAt(month),
|
|
179
|
+
savings: savingsAt(month),
|
|
180
|
+
investments,
|
|
181
|
+
total: savingsAt(month) + investments
|
|
182
|
+
};
|
|
183
|
+
})
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// src/calculators/emi.js
|
|
188
|
+
function emi({ principal, annualRate, years }) {
|
|
189
|
+
const loan = readNumber("principal", principal);
|
|
190
|
+
const i = readNumber("annualRate", annualRate) / 100 / 12;
|
|
191
|
+
const months = toMonths(years);
|
|
192
|
+
const instalment = i === 0 ? loan / months : loan * i * Math.pow(1 + i, months) / (Math.pow(1 + i, months) - 1);
|
|
193
|
+
const balances = [loan];
|
|
194
|
+
const principalPaid = [0];
|
|
195
|
+
const interestPaid = [0];
|
|
196
|
+
let balance = loan;
|
|
197
|
+
for (let month = 1; month <= months; month++) {
|
|
198
|
+
const interest = balance * i;
|
|
199
|
+
const repaid = month === months ? balance : instalment - interest;
|
|
200
|
+
balance = Math.max(0, balance - repaid);
|
|
201
|
+
balances.push(balance);
|
|
202
|
+
principalPaid.push(principalPaid[month - 1] + repaid);
|
|
203
|
+
interestPaid.push(interestPaid[month - 1] + interest);
|
|
204
|
+
}
|
|
205
|
+
const schedule = [];
|
|
206
|
+
for (let from = 0; from < months; from += 12) {
|
|
207
|
+
const to = Math.min(from + 12, months);
|
|
208
|
+
schedule.push({
|
|
209
|
+
year: schedule.length + 1,
|
|
210
|
+
principalPaid: principalPaid[to] - principalPaid[from],
|
|
211
|
+
interestPaid: interestPaid[to] - interestPaid[from],
|
|
212
|
+
balance: balances[to]
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
const totalPayment = instalment * months;
|
|
216
|
+
return {
|
|
217
|
+
emi: instalment,
|
|
218
|
+
principal: loan,
|
|
219
|
+
totalInterest: totalPayment - loan,
|
|
220
|
+
totalPayment,
|
|
221
|
+
months,
|
|
222
|
+
schedule,
|
|
223
|
+
series: yearlySeries(months, (month) => ({
|
|
224
|
+
balance: balances[month],
|
|
225
|
+
principalPaid: principalPaid[month],
|
|
226
|
+
interestPaid: interestPaid[month]
|
|
227
|
+
}))
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// src/calculators/index.js
|
|
232
|
+
var registry = { sip, lumpsum, swp, goal, emi };
|
|
233
|
+
function types() {
|
|
234
|
+
return Object.keys(registry);
|
|
235
|
+
}
|
|
236
|
+
function calculate(type, inputs) {
|
|
237
|
+
if (!Object.prototype.hasOwnProperty.call(registry, type)) {
|
|
238
|
+
throw new Error(`Unknown calculator "${type}". Available: ${types().join(", ")}.`);
|
|
239
|
+
}
|
|
240
|
+
return registry[type](inputs);
|
|
241
|
+
}
|
|
242
|
+
function register(type, fn) {
|
|
243
|
+
if (typeof type !== "string" || type === "" || typeof fn !== "function") {
|
|
244
|
+
throw new TypeError("register( type, fn ) needs a type name and a function.");
|
|
245
|
+
}
|
|
246
|
+
registry[type] = fn;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// src/format/number.js
|
|
250
|
+
var LOCALES = { indian: "en-IN", international: "en-US" };
|
|
251
|
+
var intlChecked = false;
|
|
252
|
+
var intlWorks = false;
|
|
253
|
+
function canUseIntl() {
|
|
254
|
+
if (!intlChecked) {
|
|
255
|
+
intlChecked = true;
|
|
256
|
+
try {
|
|
257
|
+
intlWorks = new Intl.NumberFormat("en-IN").format(1234567) === "12,34,567" && new Intl.NumberFormat("en-US").format(1234567) === "1,234,567";
|
|
258
|
+
} catch {
|
|
259
|
+
intlWorks = false;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
return intlWorks;
|
|
263
|
+
}
|
|
264
|
+
function readSystem(system) {
|
|
265
|
+
if (!Object.prototype.hasOwnProperty.call(LOCALES, system)) {
|
|
266
|
+
throw new RangeError(`system must be "indian" or "international", got "${system}".`);
|
|
267
|
+
}
|
|
268
|
+
return system;
|
|
269
|
+
}
|
|
270
|
+
function readDecimals(decimals) {
|
|
271
|
+
if (!Number.isInteger(decimals) || decimals < 0 || decimals > 20) {
|
|
272
|
+
throw new RangeError(`decimals must be a whole number from 0 to 20, got ${decimals}.`);
|
|
273
|
+
}
|
|
274
|
+
return decimals;
|
|
275
|
+
}
|
|
276
|
+
function groupDigits(digits, system = "indian") {
|
|
277
|
+
if (digits.length <= 3) {
|
|
278
|
+
return digits;
|
|
279
|
+
}
|
|
280
|
+
const last3 = digits.slice(-3);
|
|
281
|
+
const rest = digits.slice(0, -3);
|
|
282
|
+
const size = readSystem(system) === "indian" ? 2 : 3;
|
|
283
|
+
const pattern = new RegExp(`\\B(?=(\\d{${size}})+(?!\\d))`, "g");
|
|
284
|
+
return rest.replace(pattern, ",") + "," + last3;
|
|
285
|
+
}
|
|
286
|
+
function formatByHand(value, decimals, system) {
|
|
287
|
+
const fixed = Math.abs(value).toFixed(decimals);
|
|
288
|
+
const [whole, fraction] = fixed.split(".");
|
|
289
|
+
const sign = value < 0 && Number(fixed) !== 0 ? "-" : "";
|
|
290
|
+
return sign + groupDigits(whole, system) + (fraction ? "." + fraction : "");
|
|
291
|
+
}
|
|
292
|
+
function formatNumber(value, { system = "indian", decimals = 0 } = {}) {
|
|
293
|
+
readSystem(system);
|
|
294
|
+
readDecimals(decimals);
|
|
295
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
296
|
+
throw new TypeError(`value must be a finite number, got ${String(value)}.`);
|
|
297
|
+
}
|
|
298
|
+
const rounded = Number(value.toFixed(decimals));
|
|
299
|
+
const number = rounded === 0 ? 0 : value;
|
|
300
|
+
if (canUseIntl()) {
|
|
301
|
+
return new Intl.NumberFormat(LOCALES[system], {
|
|
302
|
+
minimumFractionDigits: decimals,
|
|
303
|
+
maximumFractionDigits: decimals,
|
|
304
|
+
useGrouping: true
|
|
305
|
+
}).format(number);
|
|
306
|
+
}
|
|
307
|
+
return formatByHand(number, decimals, system);
|
|
308
|
+
}
|
|
309
|
+
function formatCurrency(value, { symbol = "\u20B9", position = "before", system = "indian", decimals = 0 } = {}) {
|
|
310
|
+
const formatted = formatNumber(value, { system, decimals });
|
|
311
|
+
const negative = formatted.startsWith("-");
|
|
312
|
+
const digits = negative ? formatted.slice(1) : formatted;
|
|
313
|
+
const sign = negative ? "-" : "";
|
|
314
|
+
return position === "after" ? `${sign}${digits} ${symbol}` : `${sign}${symbol}${digits}`;
|
|
315
|
+
}
|
|
316
|
+
var COMPACT_UNITS = {
|
|
317
|
+
indian: [[1e7, "Cr"], [1e5, "L"], [1e3, "K"]],
|
|
318
|
+
international: [[1e12, "T"], [1e9, "B"], [1e6, "M"], [1e3, "K"]]
|
|
319
|
+
};
|
|
320
|
+
function formatCompact(value, { system = "indian", decimals = 1 } = {}) {
|
|
321
|
+
readSystem(system);
|
|
322
|
+
readDecimals(decimals);
|
|
323
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
324
|
+
throw new TypeError(`value must be a finite number, got ${String(value)}.`);
|
|
325
|
+
}
|
|
326
|
+
const absolute = Math.abs(value);
|
|
327
|
+
const sign = value < 0 ? "-" : "";
|
|
328
|
+
for (const [size, unit] of COMPACT_UNITS[system]) {
|
|
329
|
+
if (absolute >= size) {
|
|
330
|
+
const short = Number((absolute / size).toFixed(decimals));
|
|
331
|
+
return `${sign}${formatNumber(short, { system, decimals: short % 1 === 0 ? 0 : decimals })}${unit}`;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
return formatNumber(value, { system, decimals: 0 });
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// src/format/words.js
|
|
338
|
+
var ONES = [
|
|
339
|
+
"",
|
|
340
|
+
"One",
|
|
341
|
+
"Two",
|
|
342
|
+
"Three",
|
|
343
|
+
"Four",
|
|
344
|
+
"Five",
|
|
345
|
+
"Six",
|
|
346
|
+
"Seven",
|
|
347
|
+
"Eight",
|
|
348
|
+
"Nine",
|
|
349
|
+
"Ten",
|
|
350
|
+
"Eleven",
|
|
351
|
+
"Twelve",
|
|
352
|
+
"Thirteen",
|
|
353
|
+
"Fourteen",
|
|
354
|
+
"Fifteen",
|
|
355
|
+
"Sixteen",
|
|
356
|
+
"Seventeen",
|
|
357
|
+
"Eighteen",
|
|
358
|
+
"Nineteen"
|
|
359
|
+
];
|
|
360
|
+
var TENS = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"];
|
|
361
|
+
var INTERNATIONAL_SCALES = [
|
|
362
|
+
"",
|
|
363
|
+
"Thousand",
|
|
364
|
+
"Million",
|
|
365
|
+
"Billion",
|
|
366
|
+
"Trillion",
|
|
367
|
+
"Quadrillion",
|
|
368
|
+
"Quintillion",
|
|
369
|
+
"Sextillion",
|
|
370
|
+
"Septillion",
|
|
371
|
+
"Octillion",
|
|
372
|
+
"Nonillion",
|
|
373
|
+
"Decillion"
|
|
374
|
+
];
|
|
375
|
+
function belowHundred(n) {
|
|
376
|
+
if (n < 20) {
|
|
377
|
+
return ONES[n];
|
|
378
|
+
}
|
|
379
|
+
return [TENS[Math.floor(n / 10)], ONES[n % 10]].filter(Boolean).join(" ");
|
|
380
|
+
}
|
|
381
|
+
function belowThousand(n) {
|
|
382
|
+
const hundreds = Math.floor(n / 100);
|
|
383
|
+
const rest = n % 100;
|
|
384
|
+
if (!hundreds) {
|
|
385
|
+
return belowHundred(rest);
|
|
386
|
+
}
|
|
387
|
+
return `${ONES[hundreds]} Hundred` + (rest ? ` and ${belowHundred(rest)}` : "");
|
|
388
|
+
}
|
|
389
|
+
function join(parts) {
|
|
390
|
+
return parts.filter(Boolean).join(" ");
|
|
391
|
+
}
|
|
392
|
+
function indian(digits) {
|
|
393
|
+
digits = digits.replace(/^0+/, "");
|
|
394
|
+
if (digits === "") {
|
|
395
|
+
return "";
|
|
396
|
+
}
|
|
397
|
+
if (digits.length > 7) {
|
|
398
|
+
const crores = indian(digits.slice(0, -7));
|
|
399
|
+
return join([crores && `${crores} Crore`, indian(digits.slice(-7))]);
|
|
400
|
+
}
|
|
401
|
+
const n = Number(digits);
|
|
402
|
+
const lakh = Math.floor(n / 1e5);
|
|
403
|
+
const thousand = Math.floor(n % 1e5 / 1e3);
|
|
404
|
+
const rest = n % 1e3;
|
|
405
|
+
return join([
|
|
406
|
+
lakh && `${belowHundred(lakh)} Lakh`,
|
|
407
|
+
thousand && `${belowHundred(thousand)} Thousand`,
|
|
408
|
+
belowThousand(rest)
|
|
409
|
+
]);
|
|
410
|
+
}
|
|
411
|
+
function international(digits) {
|
|
412
|
+
digits = digits.replace(/^0+/, "");
|
|
413
|
+
if (digits === "") {
|
|
414
|
+
return "";
|
|
415
|
+
}
|
|
416
|
+
const maxDigits = INTERNATIONAL_SCALES.length * 3;
|
|
417
|
+
if (digits.length > maxDigits) {
|
|
418
|
+
const top = international(digits.slice(0, -(maxDigits - 3)));
|
|
419
|
+
const last = INTERNATIONAL_SCALES[INTERNATIONAL_SCALES.length - 1];
|
|
420
|
+
return join([top && `${top} ${last}`, international(digits.slice(-(maxDigits - 3)))]);
|
|
421
|
+
}
|
|
422
|
+
const parts = [];
|
|
423
|
+
for (let end = digits.length, scale = 0; end > 0; end -= 3, scale++) {
|
|
424
|
+
const group = Number(digits.slice(Math.max(0, end - 3), end));
|
|
425
|
+
if (group) {
|
|
426
|
+
parts.unshift(join([belowThousand(group), INTERNATIONAL_SCALES[scale]]));
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
return join(parts);
|
|
430
|
+
}
|
|
431
|
+
function amountInWords(value, { system = "indian" } = {}) {
|
|
432
|
+
if (system !== "indian" && system !== "international") {
|
|
433
|
+
throw new RangeError(`system must be "indian" or "international", got "${system}".`);
|
|
434
|
+
}
|
|
435
|
+
let digits;
|
|
436
|
+
let negative = false;
|
|
437
|
+
if (typeof value === "number") {
|
|
438
|
+
if (!Number.isFinite(value)) {
|
|
439
|
+
throw new TypeError(`value must be a finite number, got ${value}.`);
|
|
440
|
+
}
|
|
441
|
+
const rounded = Math.round(Math.abs(value));
|
|
442
|
+
negative = value < 0 && rounded !== 0;
|
|
443
|
+
digits = BigInt(rounded).toString();
|
|
444
|
+
} else if (typeof value === "bigint") {
|
|
445
|
+
negative = value < 0n;
|
|
446
|
+
digits = (negative ? -value : value).toString();
|
|
447
|
+
} else if (typeof value === "string" && /^-?\d+$/.test(value.trim())) {
|
|
448
|
+
const trimmed = value.trim();
|
|
449
|
+
negative = trimmed.startsWith("-") && /[1-9]/.test(trimmed);
|
|
450
|
+
digits = trimmed.replace("-", "");
|
|
451
|
+
} else {
|
|
452
|
+
throw new TypeError(`value must be a number, a BigInt or a string of digits, got ${String(value)}.`);
|
|
453
|
+
}
|
|
454
|
+
const words = system === "indian" ? indian(digits) : international(digits);
|
|
455
|
+
if (words === "") {
|
|
456
|
+
return "Zero";
|
|
457
|
+
}
|
|
458
|
+
return negative ? `Minus ${words}` : words;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
// src/index.js
|
|
462
|
+
var VERSION = true ? "1.0.1" : "development";
|
|
463
|
+
return __toCommonJS(index_exports);
|
|
464
|
+
})();
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! financial-calculators 1.0.1 | GPL-3.0-or-later | https://wpgenius.github.io/financial-calculators-js/ */
|
|
2
|
+
"use strict";var FinancialCalculators=(()=>{var P=Object.defineProperty;var Z=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var J=Object.prototype.hasOwnProperty;var X=(t,n)=>{for(var r in n)P(t,r,{get:n[r],enumerable:!0})},tt=(t,n,r,e)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of q(n))!J.call(t,o)&&o!==r&&P(t,o,{get:()=>n[o],enumerable:!(e=Z(n,o))||e.enumerable});return t};var nt=t=>tt(P({},"__esModule",{value:!0}),t);var at={};X(at,{VERSION:()=>st,amountInWords:()=>Y,calculate:()=>L,emi:()=>I,formatCompact:()=>Q,formatCurrency:()=>K,formatNumber:()=>x,goal:()=>T,groupDigits:()=>B,lumpsum:()=>M,register:()=>U,sip:()=>S,swp:()=>E,types:()=>A});function f(t,n,r=0){let e=typeof n=="string"&&n.trim()!==""?Number(n):n;if(typeof e!="number"||!Number.isFinite(e))throw new TypeError(`${t} must be a finite number, got ${String(n)}.`);if(e<r)throw new RangeError(`${t} must be at least ${r}, got ${e}.`);return e}function d(t){let n=Math.round(f("years",t)*12);if(n<1)throw new RangeError(`years must be at least one month (1/12), got ${t}.`);return n}function g(t,n){let r=[];for(let e=0;e<t;e+=12)r.push({year:e/12,month:e,...n(e)});return r.push({year:t/12,month:t,...n(t)}),r}function y(t,n,r){return n===0?t*r:t*((Math.pow(1+n,r)-1)/n)*(1+n)}function S({monthlyAmount:t,annualRate:n,years:r}){let e=f("monthlyAmount",t),o=f("annualRate",n)/100/12,i=d(r),c=y(e,o,i),u=e*i;return{invested:u,returns:c-u,total:c,months:i,series:g(i,l=>({invested:e*l,total:y(e,o,l)}))}}function M({amount:t,annualRate:n,years:r,compoundingPerYear:e=1}){let o=f("amount",t),i=f("annualRate",n)/100,c=d(r),u=f("compoundingPerYear",e,1),l=a=>o*Math.pow(1+i/u,u*a/12),m=l(c);return{invested:o,returns:m-o,total:m,months:c,series:g(c,a=>({invested:o,total:l(a)}))}}function E({investment:t,monthlyWithdrawal:n,annualRate:r,years:e}){let o=f("investment",t),i=f("monthlyWithdrawal",n),c=f("annualRate",r)/100/12,u=d(e),l=[o],m=[0],a=o,h=0,b=null;for(let s=1;s<=u;s++){let p=Math.min(i,a);a-=p,h+=p,a<=0?(a=0,b===null&&i>0&&(b=s)):a+=a*c,l.push(a),m.push(h)}return{investment:o,totalWithdrawn:h,finalBalance:a,returns:a+h-o,depletedMonth:b,months:u,series:g(u,s=>({balance:l[s],withdrawn:m[s]}))}}function T({presentCost:t,currentSavings:n=0,inflationRate:r,annualRate:e,years:o}){let i=f("presentCost",t),c=f("currentSavings",n),u=f("inflationRate",r)/100,l=f("annualRate",e)/100,m=d(o),a=l/12,h=w=>i*Math.pow(1+u,w/12),b=w=>c*Math.pow(1+l,w/12),s=h(m),p=b(m),N=Math.max(0,s-p),O=N/y(1,a,m);return{presentCost:i,futureCost:s,savingsFutureValue:p,shortfall:N,monthlyInvestment:O,totalInvested:O*m,months:m,series:g(m,w=>{let W=y(O,a,w);return{goalCost:h(w),savings:b(w),investments:W,total:b(w)+W}})}}function I({principal:t,annualRate:n,years:r}){let e=f("principal",t),o=f("annualRate",n)/100/12,i=d(r),c=o===0?e/i:e*o*Math.pow(1+o,i)/(Math.pow(1+o,i)-1),u=[e],l=[0],m=[0],a=e;for(let s=1;s<=i;s++){let p=a*o,N=s===i?a:c-p;a=Math.max(0,a-N),u.push(a),l.push(l[s-1]+N),m.push(m[s-1]+p)}let h=[];for(let s=0;s<i;s+=12){let p=Math.min(s+12,i);h.push({year:h.length+1,principalPaid:l[p]-l[s],interestPaid:m[p]-m[s],balance:u[p]})}let b=c*i;return{emi:c,principal:e,totalInterest:b-e,totalPayment:b,months:i,schedule:h,series:g(i,s=>({balance:u[s],principalPaid:l[s],interestPaid:m[s]}))}}var F={sip:S,lumpsum:M,swp:E,goal:T,emi:I};function A(){return Object.keys(F)}function L(t,n){if(!Object.prototype.hasOwnProperty.call(F,t))throw new Error(`Unknown calculator "${t}". Available: ${A().join(", ")}.`);return F[t](n)}function U(t,n){if(typeof t!="string"||t===""||typeof n!="function")throw new TypeError("register( type, fn ) needs a type name and a function.");F[t]=n}var v={indian:"en-IN",international:"en-US"},H=!1,D=!1;function et(){if(!H){H=!0;try{D=new Intl.NumberFormat("en-IN").format(1234567)==="12,34,567"&&new Intl.NumberFormat("en-US").format(1234567)==="1,234,567"}catch{D=!1}}return D}function _(t){if(!Object.prototype.hasOwnProperty.call(v,t))throw new RangeError(`system must be "indian" or "international", got "${t}".`);return t}function z(t){if(!Number.isInteger(t)||t<0||t>20)throw new RangeError(`decimals must be a whole number from 0 to 20, got ${t}.`);return t}function B(t,n="indian"){if(t.length<=3)return t;let r=t.slice(-3),e=t.slice(0,-3),o=_(n)==="indian"?2:3,i=new RegExp(`\\B(?=(\\d{${o}})+(?!\\d))`,"g");return e.replace(i,",")+","+r}function rt(t,n,r){let e=Math.abs(t).toFixed(n),[o,i]=e.split(".");return(t<0&&Number(e)!==0?"-":"")+B(o,r)+(i?"."+i:"")}function x(t,{system:n="indian",decimals:r=0}={}){if(_(n),z(r),typeof t!="number"||!Number.isFinite(t))throw new TypeError(`value must be a finite number, got ${String(t)}.`);let o=Number(t.toFixed(r))===0?0:t;return et()?new Intl.NumberFormat(v[n],{minimumFractionDigits:r,maximumFractionDigits:r,useGrouping:!0}).format(o):rt(o,r,n)}function K(t,{symbol:n="\u20B9",position:r="before",system:e="indian",decimals:o=0}={}){let i=x(t,{system:e,decimals:o}),c=i.startsWith("-"),u=c?i.slice(1):i,l=c?"-":"";return r==="after"?`${l}${u} ${n}`:`${l}${n}${u}`}var ot={indian:[[1e7,"Cr"],[1e5,"L"],[1e3,"K"]],international:[[1e12,"T"],[1e9,"B"],[1e6,"M"],[1e3,"K"]]};function Q(t,{system:n="indian",decimals:r=1}={}){if(_(n),z(r),typeof t!="number"||!Number.isFinite(t))throw new TypeError(`value must be a finite number, got ${String(t)}.`);let e=Math.abs(t),o=t<0?"-":"";for(let[i,c]of ot[n])if(e>=i){let u=Number((e/i).toFixed(r));return`${o}${x(u,{system:n,decimals:u%1===0?0:r})}${c}`}return x(t,{system:n,decimals:0})}var k=["","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"],it=["","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"],R=["","Thousand","Million","Billion","Trillion","Quadrillion","Quintillion","Sextillion","Septillion","Octillion","Nonillion","Decillion"];function C(t){return t<20?k[t]:[it[Math.floor(t/10)],k[t%10]].filter(Boolean).join(" ")}function G(t){let n=Math.floor(t/100),r=t%100;return n?`${k[n]} Hundred`+(r?` and ${C(r)}`:""):C(r)}function $(t){return t.filter(Boolean).join(" ")}function j(t){if(t=t.replace(/^0+/,""),t==="")return"";if(t.length>7){let i=j(t.slice(0,-7));return $([i&&`${i} Crore`,j(t.slice(-7))])}let n=Number(t),r=Math.floor(n/1e5),e=Math.floor(n%1e5/1e3),o=n%1e3;return $([r&&`${C(r)} Lakh`,e&&`${C(e)} Thousand`,G(o)])}function V(t){if(t=t.replace(/^0+/,""),t==="")return"";let n=R.length*3;if(t.length>n){let e=V(t.slice(0,-(n-3))),o=R[R.length-1];return $([e&&`${e} ${o}`,V(t.slice(-(n-3)))])}let r=[];for(let e=t.length,o=0;e>0;e-=3,o++){let i=Number(t.slice(Math.max(0,e-3),e));i&&r.unshift($([G(i),R[o]]))}return $(r)}function Y(t,{system:n="indian"}={}){if(n!=="indian"&&n!=="international")throw new RangeError(`system must be "indian" or "international", got "${n}".`);let r,e=!1;if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`value must be a finite number, got ${t}.`);let i=Math.round(Math.abs(t));e=t<0&&i!==0,r=BigInt(i).toString()}else if(typeof t=="bigint")e=t<0n,r=(e?-t:t).toString();else if(typeof t=="string"&&/^-?\d+$/.test(t.trim())){let i=t.trim();e=i.startsWith("-")&&/[1-9]/.test(i),r=i.replace("-","")}else throw new TypeError(`value must be a number, a BigInt or a string of digits, got ${String(t)}.`);let o=n==="indian"?j(r):V(r);return o===""?"Zero":e?`Minus ${o}`:o}var st="1.0.1";return nt(at);})();
|
package/package.json
CHANGED
|
@@ -1,6 +1,71 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wpgenius/financial-calculators",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.1",
|
|
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
|
+
"keywords": [
|
|
6
|
+
"finance",
|
|
7
|
+
"calculator",
|
|
8
|
+
"sip",
|
|
9
|
+
"emi",
|
|
10
|
+
"swp",
|
|
11
|
+
"lumpsum",
|
|
12
|
+
"indian-number-format",
|
|
13
|
+
"number-to-words"
|
|
14
|
+
],
|
|
15
|
+
"homepage": "https://wpgenius.github.io/financial-calculators-js/",
|
|
16
|
+
"bugs": "https://github.com/wpgenius/financial-calculators-js/issues",
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "git+https://github.com/wpgenius/financial-calculators-js.git"
|
|
20
|
+
},
|
|
21
|
+
"license": "GPL-3.0-or-later",
|
|
22
|
+
"author": "Team WPGenius (https://wpgenius.in)",
|
|
23
|
+
"type": "module",
|
|
24
|
+
"main": "./dist/financial-calculators.esm.js",
|
|
25
|
+
"module": "./dist/financial-calculators.esm.js",
|
|
26
|
+
"browser": "./dist/financial-calculators.min.js",
|
|
27
|
+
"unpkg": "./dist/financial-calculators.min.js",
|
|
28
|
+
"jsdelivr": "./dist/financial-calculators.min.js",
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"types": "./types/financial-calculators.d.ts",
|
|
32
|
+
"import": "./dist/financial-calculators.esm.js",
|
|
33
|
+
"default": "./dist/financial-calculators.esm.js"
|
|
34
|
+
},
|
|
35
|
+
"./src": "./src/index.js",
|
|
36
|
+
"./dist/*": "./dist/*",
|
|
37
|
+
"./package.json": "./package.json"
|
|
38
|
+
},
|
|
39
|
+
"files": [
|
|
40
|
+
"src",
|
|
41
|
+
"dist",
|
|
42
|
+
"types"
|
|
43
|
+
],
|
|
44
|
+
"sideEffects": false,
|
|
45
|
+
"engines": {
|
|
46
|
+
"node": ">=20"
|
|
47
|
+
},
|
|
48
|
+
"publishConfig": {
|
|
49
|
+
"access": "public"
|
|
50
|
+
},
|
|
51
|
+
"scripts": {
|
|
52
|
+
"lint": "eslint .",
|
|
53
|
+
"test": "node --test test/*.test.js",
|
|
54
|
+
"test:types": "tsc -p tsconfig.json",
|
|
55
|
+
"test:dist": "node scripts/check-dist.mjs",
|
|
56
|
+
"test:e2e": "playwright test",
|
|
57
|
+
"build": "node scripts/build.mjs",
|
|
58
|
+
"size": "node scripts/size.mjs",
|
|
59
|
+
"site": "node scripts/site.mjs",
|
|
60
|
+
"serve": "node scripts/serve.mjs"
|
|
61
|
+
},
|
|
62
|
+
"devDependencies": {
|
|
63
|
+
"@eslint/js": "^9.39.5",
|
|
64
|
+
"@playwright/test": "^1.65.1",
|
|
65
|
+
"esbuild": "^0.28.2",
|
|
66
|
+
"eslint": "^9.39.5",
|
|
67
|
+
"globals": "^17.14.0",
|
|
68
|
+
"typescript": "^7.0.2"
|
|
69
|
+
},
|
|
70
|
+
"types": "./types/financial-calculators.d.ts"
|
|
71
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { readNumber, toMonths, yearlySeries } from '../utils.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Loan EMI (equated monthly instalment), interest reducing monthly, with a
|
|
5
|
+
* repayment schedule per year.
|
|
6
|
+
*
|
|
7
|
+
* @param {Object} inputs
|
|
8
|
+
* @param {number} inputs.principal Loan amount.
|
|
9
|
+
* @param {number} inputs.annualRate Interest, % a year.
|
|
10
|
+
* @param {number} inputs.years Tenure in years (fractions allowed).
|
|
11
|
+
* @return {{emi: number, principal: number, totalInterest: number,
|
|
12
|
+
* totalPayment: number, months: number,
|
|
13
|
+
* schedule: Array<{year: number, principalPaid: number, interestPaid: number, balance: number}>,
|
|
14
|
+
* series: Array<{year: number, month: number, balance: number, principalPaid: number, interestPaid: number}>}}
|
|
15
|
+
* schedule: one row per loan year (the last may be shorter) with what
|
|
16
|
+
* that year paid; series: cumulative totals for charts.
|
|
17
|
+
*/
|
|
18
|
+
export function emi( { principal, annualRate, years } ) {
|
|
19
|
+
const loan = readNumber( 'principal', principal );
|
|
20
|
+
const i = readNumber( 'annualRate', annualRate ) / 100 / 12;
|
|
21
|
+
const months = toMonths( years );
|
|
22
|
+
|
|
23
|
+
const instalment = i === 0
|
|
24
|
+
? loan / months
|
|
25
|
+
: ( loan * i * Math.pow( 1 + i, months ) ) / ( Math.pow( 1 + i, months ) - 1 );
|
|
26
|
+
|
|
27
|
+
const balances = [ loan ];
|
|
28
|
+
const principalPaid = [ 0 ];
|
|
29
|
+
const interestPaid = [ 0 ];
|
|
30
|
+
let balance = loan;
|
|
31
|
+
for ( let month = 1; month <= months; month++ ) {
|
|
32
|
+
const interest = balance * i;
|
|
33
|
+
const repaid = month === months ? balance : instalment - interest;
|
|
34
|
+
balance = Math.max( 0, balance - repaid );
|
|
35
|
+
balances.push( balance );
|
|
36
|
+
principalPaid.push( principalPaid[ month - 1 ] + repaid );
|
|
37
|
+
interestPaid.push( interestPaid[ month - 1 ] + interest );
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const schedule = [];
|
|
41
|
+
for ( let from = 0; from < months; from += 12 ) {
|
|
42
|
+
const to = Math.min( from + 12, months );
|
|
43
|
+
schedule.push( {
|
|
44
|
+
year: schedule.length + 1,
|
|
45
|
+
principalPaid: principalPaid[ to ] - principalPaid[ from ],
|
|
46
|
+
interestPaid: interestPaid[ to ] - interestPaid[ from ],
|
|
47
|
+
balance: balances[ to ],
|
|
48
|
+
} );
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const totalPayment = instalment * months;
|
|
52
|
+
return {
|
|
53
|
+
emi: instalment,
|
|
54
|
+
principal: loan,
|
|
55
|
+
totalInterest: totalPayment - loan,
|
|
56
|
+
totalPayment,
|
|
57
|
+
months,
|
|
58
|
+
schedule,
|
|
59
|
+
series: yearlySeries( months, ( month ) => ( {
|
|
60
|
+
balance: balances[ month ],
|
|
61
|
+
principalPaid: principalPaid[ month ],
|
|
62
|
+
interestPaid: interestPaid[ month ],
|
|
63
|
+
} ) ),
|
|
64
|
+
};
|
|
65
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { readNumber, toMonths, yearlySeries, annuityDueValue } from '../utils.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Time-based goal: what a goal will cost after inflation, and the monthly
|
|
5
|
+
* investment (SIP, start of month) needed to reach it on top of the savings
|
|
6
|
+
* already put aside, which keep growing at the expected return.
|
|
7
|
+
* When the savings alone cover the goal, the monthly investment is 0.
|
|
8
|
+
*
|
|
9
|
+
* @param {Object} inputs
|
|
10
|
+
* @param {number} inputs.presentCost What the goal costs today.
|
|
11
|
+
* @param {number} [inputs.currentSavings=0] Savings already put aside for it.
|
|
12
|
+
* @param {number} inputs.inflationRate Inflation, % a year.
|
|
13
|
+
* @param {number} inputs.annualRate Expected return, % a year.
|
|
14
|
+
* @param {number} inputs.years Years until the goal (fractions allowed).
|
|
15
|
+
* @return {{presentCost: number, futureCost: number, savingsFutureValue: number,
|
|
16
|
+
* shortfall: number, monthlyInvestment: number, totalInvested: number,
|
|
17
|
+
* months: number,
|
|
18
|
+
* series: Array<{year: number, month: number, goalCost: number,
|
|
19
|
+
* savings: number, investments: number, total: number}>}}
|
|
20
|
+
*/
|
|
21
|
+
export function goal( { presentCost, currentSavings = 0, inflationRate, annualRate, years } ) {
|
|
22
|
+
const cost = readNumber( 'presentCost', presentCost );
|
|
23
|
+
const savings = readNumber( 'currentSavings', currentSavings );
|
|
24
|
+
const inflation = readNumber( 'inflationRate', inflationRate ) / 100;
|
|
25
|
+
const rate = readNumber( 'annualRate', annualRate ) / 100;
|
|
26
|
+
const months = toMonths( years );
|
|
27
|
+
const i = rate / 12;
|
|
28
|
+
|
|
29
|
+
const costAt = ( month ) => cost * Math.pow( 1 + inflation, month / 12 );
|
|
30
|
+
const savingsAt = ( month ) => savings * Math.pow( 1 + rate, month / 12 );
|
|
31
|
+
|
|
32
|
+
const futureCost = costAt( months );
|
|
33
|
+
const savingsFutureValue = savingsAt( months );
|
|
34
|
+
const shortfall = Math.max( 0, futureCost - savingsFutureValue );
|
|
35
|
+
const monthlyInvestment = shortfall / annuityDueValue( 1, i, months );
|
|
36
|
+
|
|
37
|
+
return {
|
|
38
|
+
presentCost: cost,
|
|
39
|
+
futureCost,
|
|
40
|
+
savingsFutureValue,
|
|
41
|
+
shortfall,
|
|
42
|
+
monthlyInvestment,
|
|
43
|
+
totalInvested: monthlyInvestment * months,
|
|
44
|
+
months,
|
|
45
|
+
series: yearlySeries( months, ( month ) => {
|
|
46
|
+
const investments = annuityDueValue( monthlyInvestment, i, month );
|
|
47
|
+
return {
|
|
48
|
+
goalCost: costAt( month ),
|
|
49
|
+
savings: savingsAt( month ),
|
|
50
|
+
investments,
|
|
51
|
+
total: savingsAt( month ) + investments,
|
|
52
|
+
};
|
|
53
|
+
} ),
|
|
54
|
+
};
|
|
55
|
+
}
|