@wpgenius/financial-calculators 0.0.0-stage → 1.0.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/LICENSE +674 -0
- package/README.md +212 -2
- package/dist/financial-calculators.esm.js +440 -0
- package/dist/financial-calculators.js +463 -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
package/README.md
CHANGED
|
@@ -1,3 +1,213 @@
|
|
|
1
|
-
#
|
|
1
|
+
# financial-calculators
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/@wpgenius/financial-calculators)
|
|
4
|
+
[](https://github.com/wpgenius/financial-calculators-js/releases/latest)
|
|
5
|
+
[](https://github.com/wpgenius/financial-calculators-js/actions/workflows/ci.yml)
|
|
6
|
+
[](LICENSE)
|
|
7
|
+
[](https://www.npmjs.com/package/@wpgenius/financial-calculators)
|
|
8
|
+
[](https://www.jsdelivr.com/package/npm/@wpgenius/financial-calculators)
|
|
9
|
+
[](https://bundlephobia.com/package/@wpgenius/financial-calculators)
|
|
10
|
+
[](package.json)
|
|
11
|
+
|
|
12
|
+
Financial calculators in plain JavaScript, with **no dependencies**: SIP, lump
|
|
13
|
+
sum, SWP, goal and loan EMI formulas with yearly series ready for charts,
|
|
14
|
+
Indian and international number formatting, and amounts in words.
|
|
15
|
+
|
|
16
|
+
**[Live demos](https://wpgenius.github.io/financial-calculators-js/)** · **[Documentation](https://wpgenius.github.io/financial-calculators-js/docs.html)** · **[Releases](https://github.com/wpgenius/financial-calculators-js/releases)**
|
|
17
|
+
|
|
18
|
+
## Features
|
|
19
|
+
|
|
20
|
+
- **Five calculators:** SIP, lump sum (yearly, quarterly or monthly compounding), SWP, time-based goal and loan EMI with a yearly repayment schedule.
|
|
21
|
+
- **Chart-ready:** every result has a `series` with one point per year.
|
|
22
|
+
- **Honest edge cases:** SWP stops at zero and reports the month the money runs out; a goal already covered by savings needs 0 a month; 0% rates work.
|
|
23
|
+
- **Indian and international formatting:** 12,34,567 or 1,234,567; 15L and 2.5Cr or 1.5M for chart axes; any currency symbol, before or after.
|
|
24
|
+
- **Amounts in words** in lakh/crore or million/billion, with no size limit.
|
|
25
|
+
- **Small and typed:** about 3 KB minified and gzipped, TypeScript types included, unit-tested against reference values. Works in browsers and Node.js 20+.
|
|
26
|
+
|
|
27
|
+
## Install
|
|
28
|
+
|
|
29
|
+
From npm:
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
npm install @wpgenius/financial-calculators
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
```js
|
|
36
|
+
import { sip, formatCurrency, amountInWords } from '@wpgenius/financial-calculators';
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Or from the jsDelivr CDN, which defines the global `FinancialCalculators`:
|
|
40
|
+
|
|
41
|
+
```html
|
|
42
|
+
<script src="https://cdn.jsdelivr.net/npm/@wpgenius/financial-calculators@1/dist/financial-calculators.min.js"></script>
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
`@1` follows the latest 1.x release; pin an exact version (such as `@1.0.0`) in
|
|
46
|
+
production. Or download `financial-calculators.min.js`, the readable
|
|
47
|
+
`financial-calculators.js` or the ES module `financial-calculators.esm.js` from
|
|
48
|
+
the [latest release](https://github.com/wpgenius/financial-calculators-js/releases/latest).
|
|
49
|
+
|
|
50
|
+
## Quick start
|
|
51
|
+
|
|
52
|
+
```html
|
|
53
|
+
<script src="https://cdn.jsdelivr.net/npm/@wpgenius/financial-calculators@1/dist/financial-calculators.min.js"></script>
|
|
54
|
+
<script>
|
|
55
|
+
const { sip, emi, formatCurrency, formatCompact, amountInWords } = FinancialCalculators;
|
|
56
|
+
|
|
57
|
+
const plan = sip( { monthlyAmount: 25000, annualRate: 12, years: 10 } );
|
|
58
|
+
formatCurrency( plan.total ); // "₹58,08,477"
|
|
59
|
+
amountInWords( plan.total ); // "Fifty Eight Lakh Eight Thousand Four Hundred and Seventy Seven"
|
|
60
|
+
plan.series.map( ( p ) => formatCompact( p.total ) ); // [ "0", "3.2L", … "58.1L" ] for a chart
|
|
61
|
+
|
|
62
|
+
const loan = emi( { principal: 3000000, annualRate: 8.5, years: 20 } );
|
|
63
|
+
formatCurrency( loan.emi ); // "₹26,035"
|
|
64
|
+
loan.schedule[ 0 ]; // { year: 1, principalPaid, interestPaid, balance }
|
|
65
|
+
</script>
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## API
|
|
69
|
+
|
|
70
|
+
| Function | Returns |
|
|
71
|
+
|---|---|
|
|
72
|
+
| `sip( { monthlyAmount, annualRate, years } )` | `{ invested, returns, total, months, series }` |
|
|
73
|
+
| `lumpsum( { amount, annualRate, years, compoundingPerYear } )` | `{ invested, returns, total, months, series }` |
|
|
74
|
+
| `swp( { investment, monthlyWithdrawal, annualRate, years } )` | `{ investment, totalWithdrawn, finalBalance, returns, depletedMonth, months, series }` |
|
|
75
|
+
| `goal( { presentCost, currentSavings, inflationRate, annualRate, years } )` | `{ futureCost, savingsFutureValue, shortfall, monthlyInvestment, totalInvested, months, series, … }` |
|
|
76
|
+
| `emi( { principal, annualRate, years } )` | `{ emi, principal, totalInterest, totalPayment, months, schedule, series }` |
|
|
77
|
+
| `calculate( type, inputs )`, `types()`, `register( type, fn )` | Run a calculator by name, list them, add one |
|
|
78
|
+
| `formatNumber( value, { system, decimals } )` | `"58,08,477"` or `"5,808,477"` |
|
|
79
|
+
| `formatCurrency( value, { symbol, position, system, decimals } )` | `"₹58,08,477"`, `"1,500 €"` |
|
|
80
|
+
| `formatCompact( value, { system, decimals } )` | `"15L"`, `"2.5Cr"`, `"1.5M"` |
|
|
81
|
+
| `amountInWords( value, { system } )` | `"Fifty Eight Lakh …"` |
|
|
82
|
+
| `groupDigits( digits, system )`, `VERSION` | Hand-made grouping; the library version |
|
|
83
|
+
|
|
84
|
+
The details follow; the [documentation](https://wpgenius.github.io/financial-calculators-js/docs.html) has the same with more examples.
|
|
85
|
+
|
|
86
|
+
### Calculators
|
|
87
|
+
|
|
88
|
+
Every calculator takes one object of inputs and returns plain numbers
|
|
89
|
+
(unrounded: round when you display them). Rates are % a year (`12` for 12%).
|
|
90
|
+
`years` may have fractions; it is rounded to whole months. Inputs may be
|
|
91
|
+
numbers or numeric strings; a missing, non-numeric or negative input throws
|
|
92
|
+
a `TypeError` or `RangeError`.
|
|
93
|
+
|
|
94
|
+
Each result has `months` and a `series`: one point at month 0, 12, 24... and a
|
|
95
|
+
last point at the final month, each with `year` and `month` plus the values
|
|
96
|
+
listed below.
|
|
97
|
+
|
|
98
|
+
#### `sip( { monthlyAmount, annualRate, years } )`
|
|
99
|
+
|
|
100
|
+
Same amount invested at the start of every month, compounded monthly.
|
|
101
|
+
|
|
102
|
+
Returns `{ invested, returns, total, months, series }`, series points
|
|
103
|
+
`{ year, month, invested, total }`.
|
|
104
|
+
|
|
105
|
+
```js
|
|
106
|
+
sip( { monthlyAmount: 25000, annualRate: 12, years: 10 } ).total; // 5808477.3…
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
#### `lumpsum( { amount, annualRate, years, compoundingPerYear = 1 } )`
|
|
110
|
+
|
|
111
|
+
One-time investment. `compoundingPerYear`: 1 yearly, 4 quarterly, 12 monthly.
|
|
112
|
+
|
|
113
|
+
Returns `{ invested, returns, total, months, series }`, series points
|
|
114
|
+
`{ year, month, invested, total }`.
|
|
115
|
+
|
|
116
|
+
#### `swp( { investment, monthlyWithdrawal, annualRate, years } )`
|
|
117
|
+
|
|
118
|
+
Fixed withdrawal at the start of every month; the rest grows monthly. The
|
|
119
|
+
balance never goes below zero.
|
|
120
|
+
|
|
121
|
+
Returns `{ investment, totalWithdrawn, finalBalance, returns, depletedMonth,
|
|
122
|
+
months, series }`. `returns` = finalBalance + totalWithdrawn − investment.
|
|
123
|
+
`depletedMonth` is the month (1-based) the money ran out, or `null`. Series
|
|
124
|
+
points `{ year, month, balance, withdrawn }` (withdrawn is cumulative).
|
|
125
|
+
|
|
126
|
+
#### `goal( { presentCost, currentSavings = 0, inflationRate, annualRate, years } )`
|
|
127
|
+
|
|
128
|
+
What a goal costs after inflation, and the monthly investment needed on top of
|
|
129
|
+
the savings already put aside (which keep growing). When the savings cover the
|
|
130
|
+
goal, the monthly investment is 0.
|
|
131
|
+
|
|
132
|
+
Returns `{ presentCost, futureCost, savingsFutureValue, shortfall,
|
|
133
|
+
monthlyInvestment, totalInvested, months, series }`, series points
|
|
134
|
+
`{ year, month, goalCost, savings, investments, total }`.
|
|
135
|
+
|
|
136
|
+
#### `emi( { principal, annualRate, years } )`
|
|
137
|
+
|
|
138
|
+
Loan instalment, interest reducing monthly.
|
|
139
|
+
|
|
140
|
+
Returns `{ emi, principal, totalInterest, totalPayment, months, schedule,
|
|
141
|
+
series }`. `schedule` has one row per loan year (the last may be shorter):
|
|
142
|
+
`{ year, principalPaid, interestPaid, balance }`. Series points
|
|
143
|
+
`{ year, month, balance, principalPaid, interestPaid }` (cumulative).
|
|
144
|
+
|
|
145
|
+
#### By name
|
|
146
|
+
|
|
147
|
+
```js
|
|
148
|
+
types(); // [ 'sip', 'lumpsum', 'swp', 'goal', 'emi' ]
|
|
149
|
+
calculate( 'emi', { principal: 100000, annualRate: 7, years: 1 } ).emi; // 8652.67…
|
|
150
|
+
register( 'myCalc', ( inputs ) => ( { … } ) ); // add or replace a calculator
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
### Formatting
|
|
154
|
+
|
|
155
|
+
`system` is `'indian'` (default) or `'international'`.
|
|
156
|
+
|
|
157
|
+
| Function | Example |
|
|
158
|
+
|---|---|
|
|
159
|
+
| `formatNumber( value, { system, decimals = 0 } )` | `formatNumber( 5808477 )` → `"58,08,477"` |
|
|
160
|
+
| `formatCurrency( value, { symbol = '₹', position = 'before', system, decimals = 0 } )` | `formatCurrency( -1500 )` → `"-₹1,500"`; `position: 'after'` → `"1,500 €"` |
|
|
161
|
+
| `formatCompact( value, { system, decimals = 1 } )` | `formatCompact( 1500000 )` → `"15L"`; international → `"1.5M"` |
|
|
162
|
+
| `amountInWords( value, { system } )` | `amountInWords( 1e12 )` → `"One Lakh Crore"` |
|
|
163
|
+
| `groupDigits( digits, system )` | `groupDigits( '1234567' )` → `"12,34,567"` |
|
|
164
|
+
|
|
165
|
+
`formatNumber` uses `Intl.NumberFormat` when the runtime has the `en-IN`
|
|
166
|
+
locale, and the same grouping by hand otherwise. `amountInWords` rounds to a
|
|
167
|
+
whole number and also takes a `BigInt` or a string of digits for amounts
|
|
168
|
+
beyond 2^53. `VERSION` is the library version.
|
|
169
|
+
|
|
170
|
+
## Contributing
|
|
171
|
+
|
|
172
|
+
Bug reports, ideas and pull requests are welcome: see [CONTRIBUTING.md](CONTRIBUTING.md) and the [code of conduct](CODE_OF_CONDUCT.md). Report security problems privately as described in [SECURITY.md](SECURITY.md); questions go to [Discussions](https://github.com/wpgenius/financial-calculators-js/discussions).
|
|
173
|
+
|
|
174
|
+
Needs Node 20 or later.
|
|
175
|
+
|
|
176
|
+
```bash
|
|
177
|
+
npm ci
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
| Command | What it does |
|
|
181
|
+
|---|---|
|
|
182
|
+
| `npm test` | Unit tests (`node --test`), including reference values from the original calculators |
|
|
183
|
+
| `npm run lint` | ESLint |
|
|
184
|
+
| `npm run build` | Builds the three files into `dist/` |
|
|
185
|
+
| `npm run test:dist` | Checks the build files and the browser global |
|
|
186
|
+
| `npm run test:types` | Checks the TypeScript types (`types/`) against `test/types.ts` |
|
|
187
|
+
| `npm run size` | Checks the minified file against its size budget |
|
|
188
|
+
| `npm run site` | Assembles the website (`site/` + `dist/`) into `_site/` |
|
|
189
|
+
| `npm run test:e2e` | Browser tests with Playwright (run `npx playwright install chromium` once, and `build` + `site` first) |
|
|
190
|
+
|
|
191
|
+
Add a calculator: one file in `src/calculators/`, one line in
|
|
192
|
+
`src/calculators/index.js`, tests in `test/`, types in `types/`, and docs.
|
|
193
|
+
|
|
194
|
+
## How changes ship
|
|
195
|
+
|
|
196
|
+
```
|
|
197
|
+
issue → branch → pull request (Closes #N) → squash merge to main → automatic release
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
- `main` is protected: changes go through pull requests, merged with squash.
|
|
201
|
+
- Every PR closes an issue (the *Linked issue* check), and CI must pass.
|
|
202
|
+
- A merge that changes `src/` makes a release: the version in `package.json`
|
|
203
|
+
goes up (a patch, or minor/major with the `release:minor` / `release:major`
|
|
204
|
+
label), `dist/` is rebuilt and `CHANGELOG.md` gets a section listing the
|
|
205
|
+
issues closed. A "Release vX.Y.Z" commit and its tag are pushed to `main`,
|
|
206
|
+
the GitHub release gets the three build files, and the package is published
|
|
207
|
+
to npm as [`@wpgenius/financial-calculators`](https://www.npmjs.com/package/@wpgenius/financial-calculators)
|
|
208
|
+
with trusted publishing. Docs, tests, CI and config changes make no release.
|
|
209
|
+
- Pull requests never edit `dist/` or `CHANGELOG.md`; the release writes them.
|
|
210
|
+
|
|
211
|
+
## License
|
|
212
|
+
|
|
213
|
+
GPL-3.0-or-later. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,440 @@
|
|
|
1
|
+
/*! financial-calculators 1.0.0 | GPL-3.0-or-later | https://wpgenius.github.io/financial-calculators-js/ */
|
|
2
|
+
|
|
3
|
+
// src/utils.js
|
|
4
|
+
function readNumber(name, value, min = 0) {
|
|
5
|
+
const number = typeof value === "string" && value.trim() !== "" ? Number(value) : value;
|
|
6
|
+
if (typeof number !== "number" || !Number.isFinite(number)) {
|
|
7
|
+
throw new TypeError(`${name} must be a finite number, got ${String(value)}.`);
|
|
8
|
+
}
|
|
9
|
+
if (number < min) {
|
|
10
|
+
throw new RangeError(`${name} must be at least ${min}, got ${number}.`);
|
|
11
|
+
}
|
|
12
|
+
return number;
|
|
13
|
+
}
|
|
14
|
+
function toMonths(years) {
|
|
15
|
+
const months = Math.round(readNumber("years", years) * 12);
|
|
16
|
+
if (months < 1) {
|
|
17
|
+
throw new RangeError(`years must be at least one month (1/12), got ${years}.`);
|
|
18
|
+
}
|
|
19
|
+
return months;
|
|
20
|
+
}
|
|
21
|
+
function yearlySeries(months, point) {
|
|
22
|
+
const series = [];
|
|
23
|
+
for (let month = 0; month < months; month += 12) {
|
|
24
|
+
series.push({ year: month / 12, month, ...point(month) });
|
|
25
|
+
}
|
|
26
|
+
series.push({ year: months / 12, month: months, ...point(months) });
|
|
27
|
+
return series;
|
|
28
|
+
}
|
|
29
|
+
function annuityDueValue(amount, i, n) {
|
|
30
|
+
if (i === 0) {
|
|
31
|
+
return amount * n;
|
|
32
|
+
}
|
|
33
|
+
return amount * ((Math.pow(1 + i, n) - 1) / i) * (1 + i);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// src/calculators/sip.js
|
|
37
|
+
function sip({ monthlyAmount, annualRate, years }) {
|
|
38
|
+
const amount = readNumber("monthlyAmount", monthlyAmount);
|
|
39
|
+
const i = readNumber("annualRate", annualRate) / 100 / 12;
|
|
40
|
+
const months = toMonths(years);
|
|
41
|
+
const total = annuityDueValue(amount, i, months);
|
|
42
|
+
const invested = amount * months;
|
|
43
|
+
return {
|
|
44
|
+
invested,
|
|
45
|
+
returns: total - invested,
|
|
46
|
+
total,
|
|
47
|
+
months,
|
|
48
|
+
series: yearlySeries(months, (month) => ({
|
|
49
|
+
invested: amount * month,
|
|
50
|
+
total: annuityDueValue(amount, i, month)
|
|
51
|
+
}))
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// src/calculators/lumpsum.js
|
|
56
|
+
function lumpsum({ amount, annualRate, years, compoundingPerYear = 1 }) {
|
|
57
|
+
const invested = readNumber("amount", amount);
|
|
58
|
+
const rate = readNumber("annualRate", annualRate) / 100;
|
|
59
|
+
const months = toMonths(years);
|
|
60
|
+
const k = readNumber("compoundingPerYear", compoundingPerYear, 1);
|
|
61
|
+
const valueAt = (month) => invested * Math.pow(1 + rate / k, k * month / 12);
|
|
62
|
+
const total = valueAt(months);
|
|
63
|
+
return {
|
|
64
|
+
invested,
|
|
65
|
+
returns: total - invested,
|
|
66
|
+
total,
|
|
67
|
+
months,
|
|
68
|
+
series: yearlySeries(months, (month) => ({
|
|
69
|
+
invested,
|
|
70
|
+
total: valueAt(month)
|
|
71
|
+
}))
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// src/calculators/swp.js
|
|
76
|
+
function swp({ investment, monthlyWithdrawal, annualRate, years }) {
|
|
77
|
+
const start = readNumber("investment", investment);
|
|
78
|
+
const withdrawal = readNumber("monthlyWithdrawal", monthlyWithdrawal);
|
|
79
|
+
const i = readNumber("annualRate", annualRate) / 100 / 12;
|
|
80
|
+
const months = toMonths(years);
|
|
81
|
+
const balances = [start];
|
|
82
|
+
const withdrawnTotals = [0];
|
|
83
|
+
let balance = start;
|
|
84
|
+
let withdrawn = 0;
|
|
85
|
+
let depletedMonth = null;
|
|
86
|
+
for (let month = 1; month <= months; month++) {
|
|
87
|
+
const take = Math.min(withdrawal, balance);
|
|
88
|
+
balance -= take;
|
|
89
|
+
withdrawn += take;
|
|
90
|
+
if (balance <= 0) {
|
|
91
|
+
balance = 0;
|
|
92
|
+
if (depletedMonth === null && withdrawal > 0) {
|
|
93
|
+
depletedMonth = month;
|
|
94
|
+
}
|
|
95
|
+
} else {
|
|
96
|
+
balance += balance * i;
|
|
97
|
+
}
|
|
98
|
+
balances.push(balance);
|
|
99
|
+
withdrawnTotals.push(withdrawn);
|
|
100
|
+
}
|
|
101
|
+
return {
|
|
102
|
+
investment: start,
|
|
103
|
+
totalWithdrawn: withdrawn,
|
|
104
|
+
finalBalance: balance,
|
|
105
|
+
returns: balance + withdrawn - start,
|
|
106
|
+
depletedMonth,
|
|
107
|
+
months,
|
|
108
|
+
series: yearlySeries(months, (month) => ({
|
|
109
|
+
balance: balances[month],
|
|
110
|
+
withdrawn: withdrawnTotals[month]
|
|
111
|
+
}))
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// src/calculators/goal.js
|
|
116
|
+
function goal({ presentCost, currentSavings = 0, inflationRate, annualRate, years }) {
|
|
117
|
+
const cost = readNumber("presentCost", presentCost);
|
|
118
|
+
const savings = readNumber("currentSavings", currentSavings);
|
|
119
|
+
const inflation = readNumber("inflationRate", inflationRate) / 100;
|
|
120
|
+
const rate = readNumber("annualRate", annualRate) / 100;
|
|
121
|
+
const months = toMonths(years);
|
|
122
|
+
const i = rate / 12;
|
|
123
|
+
const costAt = (month) => cost * Math.pow(1 + inflation, month / 12);
|
|
124
|
+
const savingsAt = (month) => savings * Math.pow(1 + rate, month / 12);
|
|
125
|
+
const futureCost = costAt(months);
|
|
126
|
+
const savingsFutureValue = savingsAt(months);
|
|
127
|
+
const shortfall = Math.max(0, futureCost - savingsFutureValue);
|
|
128
|
+
const monthlyInvestment = shortfall / annuityDueValue(1, i, months);
|
|
129
|
+
return {
|
|
130
|
+
presentCost: cost,
|
|
131
|
+
futureCost,
|
|
132
|
+
savingsFutureValue,
|
|
133
|
+
shortfall,
|
|
134
|
+
monthlyInvestment,
|
|
135
|
+
totalInvested: monthlyInvestment * months,
|
|
136
|
+
months,
|
|
137
|
+
series: yearlySeries(months, (month) => {
|
|
138
|
+
const investments = annuityDueValue(monthlyInvestment, i, month);
|
|
139
|
+
return {
|
|
140
|
+
goalCost: costAt(month),
|
|
141
|
+
savings: savingsAt(month),
|
|
142
|
+
investments,
|
|
143
|
+
total: savingsAt(month) + investments
|
|
144
|
+
};
|
|
145
|
+
})
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// src/calculators/emi.js
|
|
150
|
+
function emi({ principal, annualRate, years }) {
|
|
151
|
+
const loan = readNumber("principal", principal);
|
|
152
|
+
const i = readNumber("annualRate", annualRate) / 100 / 12;
|
|
153
|
+
const months = toMonths(years);
|
|
154
|
+
const instalment = i === 0 ? loan / months : loan * i * Math.pow(1 + i, months) / (Math.pow(1 + i, months) - 1);
|
|
155
|
+
const balances = [loan];
|
|
156
|
+
const principalPaid = [0];
|
|
157
|
+
const interestPaid = [0];
|
|
158
|
+
let balance = loan;
|
|
159
|
+
for (let month = 1; month <= months; month++) {
|
|
160
|
+
const interest = balance * i;
|
|
161
|
+
const repaid = month === months ? balance : instalment - interest;
|
|
162
|
+
balance = Math.max(0, balance - repaid);
|
|
163
|
+
balances.push(balance);
|
|
164
|
+
principalPaid.push(principalPaid[month - 1] + repaid);
|
|
165
|
+
interestPaid.push(interestPaid[month - 1] + interest);
|
|
166
|
+
}
|
|
167
|
+
const schedule = [];
|
|
168
|
+
for (let from = 0; from < months; from += 12) {
|
|
169
|
+
const to = Math.min(from + 12, months);
|
|
170
|
+
schedule.push({
|
|
171
|
+
year: schedule.length + 1,
|
|
172
|
+
principalPaid: principalPaid[to] - principalPaid[from],
|
|
173
|
+
interestPaid: interestPaid[to] - interestPaid[from],
|
|
174
|
+
balance: balances[to]
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
const totalPayment = instalment * months;
|
|
178
|
+
return {
|
|
179
|
+
emi: instalment,
|
|
180
|
+
principal: loan,
|
|
181
|
+
totalInterest: totalPayment - loan,
|
|
182
|
+
totalPayment,
|
|
183
|
+
months,
|
|
184
|
+
schedule,
|
|
185
|
+
series: yearlySeries(months, (month) => ({
|
|
186
|
+
balance: balances[month],
|
|
187
|
+
principalPaid: principalPaid[month],
|
|
188
|
+
interestPaid: interestPaid[month]
|
|
189
|
+
}))
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// src/calculators/index.js
|
|
194
|
+
var registry = { sip, lumpsum, swp, goal, emi };
|
|
195
|
+
function types() {
|
|
196
|
+
return Object.keys(registry);
|
|
197
|
+
}
|
|
198
|
+
function calculate(type, inputs) {
|
|
199
|
+
if (!Object.prototype.hasOwnProperty.call(registry, type)) {
|
|
200
|
+
throw new Error(`Unknown calculator "${type}". Available: ${types().join(", ")}.`);
|
|
201
|
+
}
|
|
202
|
+
return registry[type](inputs);
|
|
203
|
+
}
|
|
204
|
+
function register(type, fn) {
|
|
205
|
+
if (typeof type !== "string" || type === "" || typeof fn !== "function") {
|
|
206
|
+
throw new TypeError("register( type, fn ) needs a type name and a function.");
|
|
207
|
+
}
|
|
208
|
+
registry[type] = fn;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// src/format/number.js
|
|
212
|
+
var LOCALES = { indian: "en-IN", international: "en-US" };
|
|
213
|
+
var intlChecked = false;
|
|
214
|
+
var intlWorks = false;
|
|
215
|
+
function canUseIntl() {
|
|
216
|
+
if (!intlChecked) {
|
|
217
|
+
intlChecked = true;
|
|
218
|
+
try {
|
|
219
|
+
intlWorks = new Intl.NumberFormat("en-IN").format(1234567) === "12,34,567" && new Intl.NumberFormat("en-US").format(1234567) === "1,234,567";
|
|
220
|
+
} catch {
|
|
221
|
+
intlWorks = false;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
return intlWorks;
|
|
225
|
+
}
|
|
226
|
+
function readSystem(system) {
|
|
227
|
+
if (!Object.prototype.hasOwnProperty.call(LOCALES, system)) {
|
|
228
|
+
throw new RangeError(`system must be "indian" or "international", got "${system}".`);
|
|
229
|
+
}
|
|
230
|
+
return system;
|
|
231
|
+
}
|
|
232
|
+
function readDecimals(decimals) {
|
|
233
|
+
if (!Number.isInteger(decimals) || decimals < 0 || decimals > 20) {
|
|
234
|
+
throw new RangeError(`decimals must be a whole number from 0 to 20, got ${decimals}.`);
|
|
235
|
+
}
|
|
236
|
+
return decimals;
|
|
237
|
+
}
|
|
238
|
+
function groupDigits(digits, system = "indian") {
|
|
239
|
+
if (digits.length <= 3) {
|
|
240
|
+
return digits;
|
|
241
|
+
}
|
|
242
|
+
const last3 = digits.slice(-3);
|
|
243
|
+
const rest = digits.slice(0, -3);
|
|
244
|
+
const size = readSystem(system) === "indian" ? 2 : 3;
|
|
245
|
+
const pattern = new RegExp(`\\B(?=(\\d{${size}})+(?!\\d))`, "g");
|
|
246
|
+
return rest.replace(pattern, ",") + "," + last3;
|
|
247
|
+
}
|
|
248
|
+
function formatByHand(value, decimals, system) {
|
|
249
|
+
const fixed = Math.abs(value).toFixed(decimals);
|
|
250
|
+
const [whole, fraction] = fixed.split(".");
|
|
251
|
+
const sign = value < 0 && Number(fixed) !== 0 ? "-" : "";
|
|
252
|
+
return sign + groupDigits(whole, system) + (fraction ? "." + fraction : "");
|
|
253
|
+
}
|
|
254
|
+
function formatNumber(value, { system = "indian", decimals = 0 } = {}) {
|
|
255
|
+
readSystem(system);
|
|
256
|
+
readDecimals(decimals);
|
|
257
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
258
|
+
throw new TypeError(`value must be a finite number, got ${String(value)}.`);
|
|
259
|
+
}
|
|
260
|
+
const rounded = Number(value.toFixed(decimals));
|
|
261
|
+
const number = rounded === 0 ? 0 : value;
|
|
262
|
+
if (canUseIntl()) {
|
|
263
|
+
return new Intl.NumberFormat(LOCALES[system], {
|
|
264
|
+
minimumFractionDigits: decimals,
|
|
265
|
+
maximumFractionDigits: decimals,
|
|
266
|
+
useGrouping: true
|
|
267
|
+
}).format(number);
|
|
268
|
+
}
|
|
269
|
+
return formatByHand(number, decimals, system);
|
|
270
|
+
}
|
|
271
|
+
function formatCurrency(value, { symbol = "\u20B9", position = "before", system = "indian", decimals = 0 } = {}) {
|
|
272
|
+
const formatted = formatNumber(value, { system, decimals });
|
|
273
|
+
const negative = formatted.startsWith("-");
|
|
274
|
+
const digits = negative ? formatted.slice(1) : formatted;
|
|
275
|
+
const sign = negative ? "-" : "";
|
|
276
|
+
return position === "after" ? `${sign}${digits} ${symbol}` : `${sign}${symbol}${digits}`;
|
|
277
|
+
}
|
|
278
|
+
var COMPACT_UNITS = {
|
|
279
|
+
indian: [[1e7, "Cr"], [1e5, "L"], [1e3, "K"]],
|
|
280
|
+
international: [[1e12, "T"], [1e9, "B"], [1e6, "M"], [1e3, "K"]]
|
|
281
|
+
};
|
|
282
|
+
function formatCompact(value, { system = "indian", decimals = 1 } = {}) {
|
|
283
|
+
readSystem(system);
|
|
284
|
+
readDecimals(decimals);
|
|
285
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
286
|
+
throw new TypeError(`value must be a finite number, got ${String(value)}.`);
|
|
287
|
+
}
|
|
288
|
+
const absolute = Math.abs(value);
|
|
289
|
+
const sign = value < 0 ? "-" : "";
|
|
290
|
+
for (const [size, unit] of COMPACT_UNITS[system]) {
|
|
291
|
+
if (absolute >= size) {
|
|
292
|
+
const short = Number((absolute / size).toFixed(decimals));
|
|
293
|
+
return `${sign}${formatNumber(short, { system, decimals: short % 1 === 0 ? 0 : decimals })}${unit}`;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
return formatNumber(value, { system, decimals: 0 });
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// src/format/words.js
|
|
300
|
+
var ONES = [
|
|
301
|
+
"",
|
|
302
|
+
"One",
|
|
303
|
+
"Two",
|
|
304
|
+
"Three",
|
|
305
|
+
"Four",
|
|
306
|
+
"Five",
|
|
307
|
+
"Six",
|
|
308
|
+
"Seven",
|
|
309
|
+
"Eight",
|
|
310
|
+
"Nine",
|
|
311
|
+
"Ten",
|
|
312
|
+
"Eleven",
|
|
313
|
+
"Twelve",
|
|
314
|
+
"Thirteen",
|
|
315
|
+
"Fourteen",
|
|
316
|
+
"Fifteen",
|
|
317
|
+
"Sixteen",
|
|
318
|
+
"Seventeen",
|
|
319
|
+
"Eighteen",
|
|
320
|
+
"Nineteen"
|
|
321
|
+
];
|
|
322
|
+
var TENS = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"];
|
|
323
|
+
var INTERNATIONAL_SCALES = [
|
|
324
|
+
"",
|
|
325
|
+
"Thousand",
|
|
326
|
+
"Million",
|
|
327
|
+
"Billion",
|
|
328
|
+
"Trillion",
|
|
329
|
+
"Quadrillion",
|
|
330
|
+
"Quintillion",
|
|
331
|
+
"Sextillion",
|
|
332
|
+
"Septillion",
|
|
333
|
+
"Octillion",
|
|
334
|
+
"Nonillion",
|
|
335
|
+
"Decillion"
|
|
336
|
+
];
|
|
337
|
+
function belowHundred(n) {
|
|
338
|
+
if (n < 20) {
|
|
339
|
+
return ONES[n];
|
|
340
|
+
}
|
|
341
|
+
return [TENS[Math.floor(n / 10)], ONES[n % 10]].filter(Boolean).join(" ");
|
|
342
|
+
}
|
|
343
|
+
function belowThousand(n) {
|
|
344
|
+
const hundreds = Math.floor(n / 100);
|
|
345
|
+
const rest = n % 100;
|
|
346
|
+
if (!hundreds) {
|
|
347
|
+
return belowHundred(rest);
|
|
348
|
+
}
|
|
349
|
+
return `${ONES[hundreds]} Hundred` + (rest ? ` and ${belowHundred(rest)}` : "");
|
|
350
|
+
}
|
|
351
|
+
function join(parts) {
|
|
352
|
+
return parts.filter(Boolean).join(" ");
|
|
353
|
+
}
|
|
354
|
+
function indian(digits) {
|
|
355
|
+
digits = digits.replace(/^0+/, "");
|
|
356
|
+
if (digits === "") {
|
|
357
|
+
return "";
|
|
358
|
+
}
|
|
359
|
+
if (digits.length > 7) {
|
|
360
|
+
const crores = indian(digits.slice(0, -7));
|
|
361
|
+
return join([crores && `${crores} Crore`, indian(digits.slice(-7))]);
|
|
362
|
+
}
|
|
363
|
+
const n = Number(digits);
|
|
364
|
+
const lakh = Math.floor(n / 1e5);
|
|
365
|
+
const thousand = Math.floor(n % 1e5 / 1e3);
|
|
366
|
+
const rest = n % 1e3;
|
|
367
|
+
return join([
|
|
368
|
+
lakh && `${belowHundred(lakh)} Lakh`,
|
|
369
|
+
thousand && `${belowHundred(thousand)} Thousand`,
|
|
370
|
+
belowThousand(rest)
|
|
371
|
+
]);
|
|
372
|
+
}
|
|
373
|
+
function international(digits) {
|
|
374
|
+
digits = digits.replace(/^0+/, "");
|
|
375
|
+
if (digits === "") {
|
|
376
|
+
return "";
|
|
377
|
+
}
|
|
378
|
+
const maxDigits = INTERNATIONAL_SCALES.length * 3;
|
|
379
|
+
if (digits.length > maxDigits) {
|
|
380
|
+
const top = international(digits.slice(0, -(maxDigits - 3)));
|
|
381
|
+
const last = INTERNATIONAL_SCALES[INTERNATIONAL_SCALES.length - 1];
|
|
382
|
+
return join([top && `${top} ${last}`, international(digits.slice(-(maxDigits - 3)))]);
|
|
383
|
+
}
|
|
384
|
+
const parts = [];
|
|
385
|
+
for (let end = digits.length, scale = 0; end > 0; end -= 3, scale++) {
|
|
386
|
+
const group = Number(digits.slice(Math.max(0, end - 3), end));
|
|
387
|
+
if (group) {
|
|
388
|
+
parts.unshift(join([belowThousand(group), INTERNATIONAL_SCALES[scale]]));
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
return join(parts);
|
|
392
|
+
}
|
|
393
|
+
function amountInWords(value, { system = "indian" } = {}) {
|
|
394
|
+
if (system !== "indian" && system !== "international") {
|
|
395
|
+
throw new RangeError(`system must be "indian" or "international", got "${system}".`);
|
|
396
|
+
}
|
|
397
|
+
let digits;
|
|
398
|
+
let negative = false;
|
|
399
|
+
if (typeof value === "number") {
|
|
400
|
+
if (!Number.isFinite(value)) {
|
|
401
|
+
throw new TypeError(`value must be a finite number, got ${value}.`);
|
|
402
|
+
}
|
|
403
|
+
const rounded = Math.round(Math.abs(value));
|
|
404
|
+
negative = value < 0 && rounded !== 0;
|
|
405
|
+
digits = BigInt(rounded).toString();
|
|
406
|
+
} else if (typeof value === "bigint") {
|
|
407
|
+
negative = value < 0n;
|
|
408
|
+
digits = (negative ? -value : value).toString();
|
|
409
|
+
} else if (typeof value === "string" && /^-?\d+$/.test(value.trim())) {
|
|
410
|
+
const trimmed = value.trim();
|
|
411
|
+
negative = trimmed.startsWith("-") && /[1-9]/.test(trimmed);
|
|
412
|
+
digits = trimmed.replace("-", "");
|
|
413
|
+
} else {
|
|
414
|
+
throw new TypeError(`value must be a number, a BigInt or a string of digits, got ${String(value)}.`);
|
|
415
|
+
}
|
|
416
|
+
const words = system === "indian" ? indian(digits) : international(digits);
|
|
417
|
+
if (words === "") {
|
|
418
|
+
return "Zero";
|
|
419
|
+
}
|
|
420
|
+
return negative ? `Minus ${words}` : words;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
// src/index.js
|
|
424
|
+
var VERSION = true ? "1.0.0" : "development";
|
|
425
|
+
export {
|
|
426
|
+
VERSION,
|
|
427
|
+
amountInWords,
|
|
428
|
+
calculate,
|
|
429
|
+
emi,
|
|
430
|
+
formatCompact,
|
|
431
|
+
formatCurrency,
|
|
432
|
+
formatNumber,
|
|
433
|
+
goal,
|
|
434
|
+
groupDigits,
|
|
435
|
+
lumpsum,
|
|
436
|
+
register,
|
|
437
|
+
sip,
|
|
438
|
+
swp,
|
|
439
|
+
types
|
|
440
|
+
};
|