@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,51 @@
|
|
|
1
|
+
import { sip } from './sip.js';
|
|
2
|
+
import { lumpsum } from './lumpsum.js';
|
|
3
|
+
import { swp } from './swp.js';
|
|
4
|
+
import { goal } from './goal.js';
|
|
5
|
+
import { emi } from './emi.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Every calculator, by type. New calculators (FD, step-up SIP, RD, PPF, CAGR,
|
|
9
|
+
* retirement) are added as a file in this folder and one line here.
|
|
10
|
+
*/
|
|
11
|
+
const registry = { sip, lumpsum, swp, goal, emi };
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The calculator types available.
|
|
15
|
+
*
|
|
16
|
+
* @return {string[]} Types, e.g. [ 'sip', 'lumpsum', 'swp', 'goal', 'emi' ].
|
|
17
|
+
*/
|
|
18
|
+
export function types() {
|
|
19
|
+
return Object.keys( registry );
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Runs a calculator by type.
|
|
24
|
+
*
|
|
25
|
+
* @param {string} type Calculator type (see types()).
|
|
26
|
+
* @param {Object} inputs That calculator's inputs.
|
|
27
|
+
* @return {Object} That calculator's result.
|
|
28
|
+
* @throws {Error} When the type is unknown.
|
|
29
|
+
*/
|
|
30
|
+
export function calculate( type, inputs ) {
|
|
31
|
+
if ( ! Object.prototype.hasOwnProperty.call( registry, type ) ) {
|
|
32
|
+
throw new Error( `Unknown calculator "${ type }". Available: ${ types().join( ', ' ) }.` );
|
|
33
|
+
}
|
|
34
|
+
return registry[ type ]( inputs );
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Adds or replaces a calculator, e.g. to try a new one before it is part of
|
|
39
|
+
* the library.
|
|
40
|
+
*
|
|
41
|
+
* @param {string} type Calculator type.
|
|
42
|
+
* @param {function(Object): Object} fn Takes the inputs, returns the result.
|
|
43
|
+
*/
|
|
44
|
+
export function register( type, fn ) {
|
|
45
|
+
if ( typeof type !== 'string' || type === '' || typeof fn !== 'function' ) {
|
|
46
|
+
throw new TypeError( 'register( type, fn ) needs a type name and a function.' );
|
|
47
|
+
}
|
|
48
|
+
registry[ type ] = fn;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export { sip, lumpsum, swp, goal, emi };
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { readNumber, toMonths, yearlySeries } from '../utils.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Lump sum (one-time investment), compounded a given number of times a year.
|
|
5
|
+
*
|
|
6
|
+
* @param {Object} inputs
|
|
7
|
+
* @param {number} inputs.amount Amount invested once, at the start.
|
|
8
|
+
* @param {number} inputs.annualRate Expected return, % a year.
|
|
9
|
+
* @param {number} inputs.years Duration in years (fractions allowed).
|
|
10
|
+
* @param {number} [inputs.compoundingPerYear=1] 1 yearly, 4 quarterly, 12 monthly.
|
|
11
|
+
* @return {{invested: number, returns: number, total: number, months: number,
|
|
12
|
+
* series: Array<{year: number, month: number, invested: number, total: number}>}}
|
|
13
|
+
*/
|
|
14
|
+
export function lumpsum( { amount, annualRate, years, compoundingPerYear = 1 } ) {
|
|
15
|
+
const invested = readNumber( 'amount', amount );
|
|
16
|
+
const rate = readNumber( 'annualRate', annualRate ) / 100;
|
|
17
|
+
const months = toMonths( years );
|
|
18
|
+
const k = readNumber( 'compoundingPerYear', compoundingPerYear, 1 );
|
|
19
|
+
|
|
20
|
+
const valueAt = ( month ) => invested * Math.pow( 1 + rate / k, ( k * month ) / 12 );
|
|
21
|
+
const total = valueAt( months );
|
|
22
|
+
|
|
23
|
+
return {
|
|
24
|
+
invested,
|
|
25
|
+
returns: total - invested,
|
|
26
|
+
total,
|
|
27
|
+
months,
|
|
28
|
+
series: yearlySeries( months, ( month ) => ( {
|
|
29
|
+
invested,
|
|
30
|
+
total: valueAt( month ),
|
|
31
|
+
} ) ),
|
|
32
|
+
};
|
|
33
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { readNumber, toMonths, yearlySeries, annuityDueValue } from '../utils.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* SIP (systematic investment plan): the same amount invested at the start of
|
|
5
|
+
* every month, compounded monthly.
|
|
6
|
+
*
|
|
7
|
+
* @param {Object} inputs
|
|
8
|
+
* @param {number} inputs.monthlyAmount Amount invested each month.
|
|
9
|
+
* @param {number} inputs.annualRate Expected return, % a year (12 for 12%).
|
|
10
|
+
* @param {number} inputs.years Duration in years (fractions allowed).
|
|
11
|
+
* @return {{invested: number, returns: number, total: number, months: number,
|
|
12
|
+
* series: Array<{year: number, month: number, invested: number, total: number}>}}
|
|
13
|
+
*/
|
|
14
|
+
export function sip( { monthlyAmount, annualRate, years } ) {
|
|
15
|
+
const amount = readNumber( 'monthlyAmount', monthlyAmount );
|
|
16
|
+
const i = readNumber( 'annualRate', annualRate ) / 100 / 12;
|
|
17
|
+
const months = toMonths( years );
|
|
18
|
+
|
|
19
|
+
const total = annuityDueValue( amount, i, months );
|
|
20
|
+
const invested = amount * months;
|
|
21
|
+
|
|
22
|
+
return {
|
|
23
|
+
invested,
|
|
24
|
+
returns: total - invested,
|
|
25
|
+
total,
|
|
26
|
+
months,
|
|
27
|
+
series: yearlySeries( months, ( month ) => ( {
|
|
28
|
+
invested: amount * month,
|
|
29
|
+
total: annuityDueValue( amount, i, month ),
|
|
30
|
+
} ) ),
|
|
31
|
+
};
|
|
32
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { readNumber, toMonths, yearlySeries } from '../utils.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* SWP (systematic withdrawal plan): a fixed amount withdrawn at the start of
|
|
5
|
+
* every month; the rest earns the expected return, compounded monthly.
|
|
6
|
+
* The balance never goes below zero: when it runs out, the last withdrawal
|
|
7
|
+
* is whatever is left and depletedMonth says when that happened.
|
|
8
|
+
*
|
|
9
|
+
* @param {Object} inputs
|
|
10
|
+
* @param {number} inputs.investment Amount invested at the start.
|
|
11
|
+
* @param {number} inputs.monthlyWithdrawal Amount withdrawn each month.
|
|
12
|
+
* @param {number} inputs.annualRate Expected return, % a year.
|
|
13
|
+
* @param {number} inputs.years Duration in years (fractions allowed).
|
|
14
|
+
* @return {{investment: number, totalWithdrawn: number, finalBalance: number,
|
|
15
|
+
* returns: number, depletedMonth: (number|null), months: number,
|
|
16
|
+
* series: Array<{year: number, month: number, balance: number, withdrawn: number}>}}
|
|
17
|
+
* returns = finalBalance + totalWithdrawn − investment.
|
|
18
|
+
* depletedMonth is the month (1-based) the balance reached zero, or null.
|
|
19
|
+
*/
|
|
20
|
+
export function swp( { investment, monthlyWithdrawal, annualRate, years } ) {
|
|
21
|
+
const start = readNumber( 'investment', investment );
|
|
22
|
+
const withdrawal = readNumber( 'monthlyWithdrawal', monthlyWithdrawal );
|
|
23
|
+
const i = readNumber( 'annualRate', annualRate ) / 100 / 12;
|
|
24
|
+
const months = toMonths( years );
|
|
25
|
+
|
|
26
|
+
const balances = [ start ];
|
|
27
|
+
const withdrawnTotals = [ 0 ];
|
|
28
|
+
let balance = start;
|
|
29
|
+
let withdrawn = 0;
|
|
30
|
+
let depletedMonth = null;
|
|
31
|
+
|
|
32
|
+
for ( let month = 1; month <= months; month++ ) {
|
|
33
|
+
const take = Math.min( withdrawal, balance );
|
|
34
|
+
balance -= take;
|
|
35
|
+
withdrawn += take;
|
|
36
|
+
if ( balance <= 0 ) {
|
|
37
|
+
balance = 0;
|
|
38
|
+
if ( depletedMonth === null && withdrawal > 0 ) {
|
|
39
|
+
depletedMonth = month;
|
|
40
|
+
}
|
|
41
|
+
} else {
|
|
42
|
+
balance += balance * i;
|
|
43
|
+
}
|
|
44
|
+
balances.push( balance );
|
|
45
|
+
withdrawnTotals.push( withdrawn );
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
return {
|
|
49
|
+
investment: start,
|
|
50
|
+
totalWithdrawn: withdrawn,
|
|
51
|
+
finalBalance: balance,
|
|
52
|
+
returns: balance + withdrawn - start,
|
|
53
|
+
depletedMonth,
|
|
54
|
+
months,
|
|
55
|
+
series: yearlySeries( months, ( month ) => ( {
|
|
56
|
+
balance: balances[ month ],
|
|
57
|
+
withdrawn: withdrawnTotals[ month ],
|
|
58
|
+
} ) ),
|
|
59
|
+
};
|
|
60
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Number formatting in the Indian (12,34,567) or international (1,234,567)
|
|
3
|
+
* system. Uses Intl.NumberFormat when the runtime supports the en-IN locale,
|
|
4
|
+
* and the same grouping by hand otherwise, so the output never depends on
|
|
5
|
+
* which locales a browser or Node build ships.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
const LOCALES = { indian: 'en-IN', international: 'en-US' };
|
|
9
|
+
|
|
10
|
+
let intlChecked = false;
|
|
11
|
+
let intlWorks = false;
|
|
12
|
+
|
|
13
|
+
function canUseIntl() {
|
|
14
|
+
if ( ! intlChecked ) {
|
|
15
|
+
intlChecked = true;
|
|
16
|
+
try {
|
|
17
|
+
intlWorks =
|
|
18
|
+
new Intl.NumberFormat( 'en-IN' ).format( 1234567 ) === '12,34,567' &&
|
|
19
|
+
new Intl.NumberFormat( 'en-US' ).format( 1234567 ) === '1,234,567';
|
|
20
|
+
} catch {
|
|
21
|
+
intlWorks = false;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return intlWorks;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function readSystem( system ) {
|
|
28
|
+
if ( ! Object.prototype.hasOwnProperty.call( LOCALES, system ) ) {
|
|
29
|
+
throw new RangeError( `system must be "indian" or "international", got "${ system }".` );
|
|
30
|
+
}
|
|
31
|
+
return system;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function readDecimals( decimals ) {
|
|
35
|
+
if ( ! Number.isInteger( decimals ) || decimals < 0 || decimals > 20 ) {
|
|
36
|
+
throw new RangeError( `decimals must be a whole number from 0 to 20, got ${ decimals }.` );
|
|
37
|
+
}
|
|
38
|
+
return decimals;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Groups the digits of a non-negative whole-number string.
|
|
43
|
+
*
|
|
44
|
+
* @param {string} digits Digits only, e.g. "1234567".
|
|
45
|
+
* @param {string} system "indian" or "international".
|
|
46
|
+
* @return {string} e.g. "12,34,567" or "1,234,567".
|
|
47
|
+
*/
|
|
48
|
+
export function groupDigits( digits, system = 'indian' ) {
|
|
49
|
+
if ( digits.length <= 3 ) {
|
|
50
|
+
return digits;
|
|
51
|
+
}
|
|
52
|
+
const last3 = digits.slice( -3 );
|
|
53
|
+
const rest = digits.slice( 0, -3 );
|
|
54
|
+
const size = readSystem( system ) === 'indian' ? 2 : 3;
|
|
55
|
+
const pattern = new RegExp( `\\B(?=(\\d{${ size }})+(?!\\d))`, 'g' );
|
|
56
|
+
return rest.replace( pattern, ',' ) + ',' + last3;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function formatByHand( value, decimals, system ) {
|
|
60
|
+
const fixed = Math.abs( value ).toFixed( decimals );
|
|
61
|
+
const [ whole, fraction ] = fixed.split( '.' );
|
|
62
|
+
const sign = value < 0 && Number( fixed ) !== 0 ? '-' : '';
|
|
63
|
+
return sign + groupDigits( whole, system ) + ( fraction ? '.' + fraction : '' );
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Formats a number with grouping separators.
|
|
68
|
+
*
|
|
69
|
+
* @param {number} value
|
|
70
|
+
* @param {Object} [options]
|
|
71
|
+
* @param {string} [options.system='indian'] "indian" or "international".
|
|
72
|
+
* @param {number} [options.decimals=0] Digits after the decimal point.
|
|
73
|
+
* @return {string} e.g. formatNumber( 5808477 ) → "58,08,477".
|
|
74
|
+
*/
|
|
75
|
+
export function formatNumber( value, { system = 'indian', decimals = 0 } = {} ) {
|
|
76
|
+
readSystem( system );
|
|
77
|
+
readDecimals( decimals );
|
|
78
|
+
if ( typeof value !== 'number' || ! Number.isFinite( value ) ) {
|
|
79
|
+
throw new TypeError( `value must be a finite number, got ${ String( value ) }.` );
|
|
80
|
+
}
|
|
81
|
+
// Avoid "-0" for values that round to zero.
|
|
82
|
+
const rounded = Number( value.toFixed( decimals ) );
|
|
83
|
+
const number = rounded === 0 ? 0 : value;
|
|
84
|
+
if ( canUseIntl() ) {
|
|
85
|
+
return new Intl.NumberFormat( LOCALES[ system ], {
|
|
86
|
+
minimumFractionDigits: decimals,
|
|
87
|
+
maximumFractionDigits: decimals,
|
|
88
|
+
useGrouping: true,
|
|
89
|
+
} ).format( number );
|
|
90
|
+
}
|
|
91
|
+
return formatByHand( number, decimals, system );
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Formats an amount of money: the currency symbol plus the grouped number.
|
|
96
|
+
*
|
|
97
|
+
* @param {number} value
|
|
98
|
+
* @param {Object} [options]
|
|
99
|
+
* @param {string} [options.symbol='₹'] Currency symbol.
|
|
100
|
+
* @param {string} [options.position='before'] "before" (₹100) or "after" (100 €).
|
|
101
|
+
* @param {string} [options.system='indian'] "indian" or "international".
|
|
102
|
+
* @param {number} [options.decimals=0] Digits after the decimal point.
|
|
103
|
+
* @return {string} e.g. formatCurrency( -1500 ) → "-₹1,500".
|
|
104
|
+
*/
|
|
105
|
+
export function formatCurrency( value, { symbol = '₹', position = 'before', system = 'indian', decimals = 0 } = {} ) {
|
|
106
|
+
const formatted = formatNumber( value, { system, decimals } );
|
|
107
|
+
const negative = formatted.startsWith( '-' );
|
|
108
|
+
const digits = negative ? formatted.slice( 1 ) : formatted;
|
|
109
|
+
const sign = negative ? '-' : '';
|
|
110
|
+
return position === 'after' ? `${ sign }${ digits } ${ symbol }` : `${ sign }${ symbol }${ digits }`;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const COMPACT_UNITS = {
|
|
114
|
+
indian: [ [ 1e7, 'Cr' ], [ 1e5, 'L' ], [ 1e3, 'K' ] ],
|
|
115
|
+
international: [ [ 1e12, 'T' ], [ 1e9, 'B' ], [ 1e6, 'M' ], [ 1e3, 'K' ] ],
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Short form for chart axes and tight spaces.
|
|
120
|
+
*
|
|
121
|
+
* @param {number} value
|
|
122
|
+
* @param {Object} [options]
|
|
123
|
+
* @param {string} [options.system='indian'] "indian" (K, L, Cr) or "international" (K, M, B, T).
|
|
124
|
+
* @param {number} [options.decimals=1] Most digits after the decimal point.
|
|
125
|
+
* @return {string} e.g. 1500000 → "15L" (indian) or "1.5M" (international).
|
|
126
|
+
*/
|
|
127
|
+
export function formatCompact( value, { system = 'indian', decimals = 1 } = {} ) {
|
|
128
|
+
readSystem( system );
|
|
129
|
+
readDecimals( decimals );
|
|
130
|
+
if ( typeof value !== 'number' || ! Number.isFinite( value ) ) {
|
|
131
|
+
throw new TypeError( `value must be a finite number, got ${ String( value ) }.` );
|
|
132
|
+
}
|
|
133
|
+
const absolute = Math.abs( value );
|
|
134
|
+
const sign = value < 0 ? '-' : '';
|
|
135
|
+
for ( const [ size, unit ] of COMPACT_UNITS[ system ] ) {
|
|
136
|
+
if ( absolute >= size ) {
|
|
137
|
+
const short = Number( ( absolute / size ).toFixed( decimals ) );
|
|
138
|
+
return `${ sign }${ formatNumber( short, { system, decimals: short % 1 === 0 ? 0 : decimals } ) }${ unit }`;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
return formatNumber( value, { system, decimals: 0 } );
|
|
142
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Amounts in words, in the Indian (lakh, crore) or international (million,
|
|
3
|
+
* billion...) system, with no limit on size: above the largest named unit
|
|
4
|
+
* the words repeat ("One Thousand Crore", "One Thousand Decillion").
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
const ONES = [ '', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',
|
|
8
|
+
'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen',
|
|
9
|
+
'Eighteen', 'Nineteen' ];
|
|
10
|
+
const TENS = [ '', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety' ];
|
|
11
|
+
const INTERNATIONAL_SCALES = [ '', 'Thousand', 'Million', 'Billion', 'Trillion', 'Quadrillion',
|
|
12
|
+
'Quintillion', 'Sextillion', 'Septillion', 'Octillion', 'Nonillion', 'Decillion' ];
|
|
13
|
+
|
|
14
|
+
// 0–99.
|
|
15
|
+
function belowHundred( n ) {
|
|
16
|
+
if ( n < 20 ) {
|
|
17
|
+
return ONES[ n ];
|
|
18
|
+
}
|
|
19
|
+
return [ TENS[ Math.floor( n / 10 ) ], ONES[ n % 10 ] ].filter( Boolean ).join( ' ' );
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// 0–999: "Four Hundred and Seventy Seven".
|
|
23
|
+
function belowThousand( n ) {
|
|
24
|
+
const hundreds = Math.floor( n / 100 );
|
|
25
|
+
const rest = n % 100;
|
|
26
|
+
if ( ! hundreds ) {
|
|
27
|
+
return belowHundred( rest );
|
|
28
|
+
}
|
|
29
|
+
return `${ ONES[ hundreds ] } Hundred` + ( rest ? ` and ${ belowHundred( rest ) }` : '' );
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function join( parts ) {
|
|
33
|
+
return parts.filter( Boolean ).join( ' ' );
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Digits → words, Indian system: ...crore, lakh, thousand, hundreds.
|
|
37
|
+
function indian( digits ) {
|
|
38
|
+
digits = digits.replace( /^0+/, '' );
|
|
39
|
+
if ( digits === '' ) {
|
|
40
|
+
return '';
|
|
41
|
+
}
|
|
42
|
+
if ( digits.length > 7 ) {
|
|
43
|
+
const crores = indian( digits.slice( 0, -7 ) );
|
|
44
|
+
return join( [ crores && `${ crores } Crore`, indian( digits.slice( -7 ) ) ] );
|
|
45
|
+
}
|
|
46
|
+
const n = Number( digits );
|
|
47
|
+
const lakh = Math.floor( n / 1e5 );
|
|
48
|
+
const thousand = Math.floor( ( n % 1e5 ) / 1e3 );
|
|
49
|
+
const rest = n % 1e3;
|
|
50
|
+
return join( [
|
|
51
|
+
lakh && `${ belowHundred( lakh ) } Lakh`,
|
|
52
|
+
thousand && `${ belowHundred( thousand ) } Thousand`,
|
|
53
|
+
belowThousand( rest ),
|
|
54
|
+
] );
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Digits → words, international system: groups of three.
|
|
58
|
+
function international( digits ) {
|
|
59
|
+
digits = digits.replace( /^0+/, '' );
|
|
60
|
+
if ( digits === '' ) {
|
|
61
|
+
return '';
|
|
62
|
+
}
|
|
63
|
+
const maxDigits = INTERNATIONAL_SCALES.length * 3;
|
|
64
|
+
if ( digits.length > maxDigits ) {
|
|
65
|
+
const top = international( digits.slice( 0, -( maxDigits - 3 ) ) );
|
|
66
|
+
const last = INTERNATIONAL_SCALES[ INTERNATIONAL_SCALES.length - 1 ];
|
|
67
|
+
return join( [ top && `${ top } ${ last }`, international( digits.slice( -( maxDigits - 3 ) ) ) ] );
|
|
68
|
+
}
|
|
69
|
+
const parts = [];
|
|
70
|
+
for ( let end = digits.length, scale = 0; end > 0; end -= 3, scale++ ) {
|
|
71
|
+
const group = Number( digits.slice( Math.max( 0, end - 3 ), end ) );
|
|
72
|
+
if ( group ) {
|
|
73
|
+
parts.unshift( join( [ belowThousand( group ), INTERNATIONAL_SCALES[ scale ] ] ) );
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return join( parts );
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Spells out an amount, rounded to a whole number.
|
|
81
|
+
*
|
|
82
|
+
* @param {(number|bigint|string)} value A number, a BigInt, or a string of
|
|
83
|
+
* digits (for amounts beyond 2^53).
|
|
84
|
+
* @param {Object} [options]
|
|
85
|
+
* @param {string} [options.system='indian'] "indian" or "international".
|
|
86
|
+
* @return {string} e.g. 2808477 → "Twenty Eight Lakh Eight Thousand Four Hundred and Seventy Seven".
|
|
87
|
+
*/
|
|
88
|
+
export function amountInWords( value, { system = 'indian' } = {} ) {
|
|
89
|
+
if ( system !== 'indian' && system !== 'international' ) {
|
|
90
|
+
throw new RangeError( `system must be "indian" or "international", got "${ system }".` );
|
|
91
|
+
}
|
|
92
|
+
let digits;
|
|
93
|
+
let negative = false;
|
|
94
|
+
if ( typeof value === 'number' ) {
|
|
95
|
+
if ( ! Number.isFinite( value ) ) {
|
|
96
|
+
throw new TypeError( `value must be a finite number, got ${ value }.` );
|
|
97
|
+
}
|
|
98
|
+
const rounded = Math.round( Math.abs( value ) );
|
|
99
|
+
negative = value < 0 && rounded !== 0;
|
|
100
|
+
digits = BigInt( rounded ).toString();
|
|
101
|
+
} else if ( typeof value === 'bigint' ) {
|
|
102
|
+
negative = value < 0n;
|
|
103
|
+
digits = ( negative ? -value : value ).toString();
|
|
104
|
+
} else if ( typeof value === 'string' && /^-?\d+$/.test( value.trim() ) ) {
|
|
105
|
+
const trimmed = value.trim();
|
|
106
|
+
negative = trimmed.startsWith( '-' ) && /[1-9]/.test( trimmed );
|
|
107
|
+
digits = trimmed.replace( '-', '' );
|
|
108
|
+
} else {
|
|
109
|
+
throw new TypeError( `value must be a number, a BigInt or a string of digits, got ${ String( value ) }.` );
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const words = system === 'indian' ? indian( digits ) : international( digits );
|
|
113
|
+
if ( words === '' ) {
|
|
114
|
+
return 'Zero';
|
|
115
|
+
}
|
|
116
|
+
return negative ? `Minus ${ words }` : words;
|
|
117
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* financial-calculators: financial formulas, number formatting and amounts
|
|
3
|
+
* in words. No dependencies.
|
|
4
|
+
*
|
|
5
|
+
* Browser: the build files define the global `FinancialCalculators`.
|
|
6
|
+
* Modules: import { sip, formatNumber } from '@wpgenius/financial-calculators'.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export { sip, lumpsum, swp, goal, emi, calculate, register, types } from './calculators/index.js';
|
|
10
|
+
export { formatNumber, formatCurrency, formatCompact, groupDigits } from './format/number.js';
|
|
11
|
+
export { amountInWords } from './format/words.js';
|
|
12
|
+
|
|
13
|
+
/* global __VERSION__ */
|
|
14
|
+
/** Library version, stamped in by the build ("development" when running from src/). */
|
|
15
|
+
export const VERSION = typeof __VERSION__ === 'string' ? __VERSION__ : 'development';
|
package/src/utils.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared helpers for the calculators: input checks and the yearly series.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Reads a numeric input. Accepts numbers and numeric strings.
|
|
7
|
+
*
|
|
8
|
+
* @param {string} name Input name, for the error message.
|
|
9
|
+
* @param {*} value Value to read.
|
|
10
|
+
* @param {number} [min=0] Smallest allowed value.
|
|
11
|
+
* @return {number} The value as a number.
|
|
12
|
+
* @throws {TypeError} When the value is not a finite number.
|
|
13
|
+
* @throws {RangeError} When the value is below min.
|
|
14
|
+
*/
|
|
15
|
+
export function readNumber( name, value, min = 0 ) {
|
|
16
|
+
const number = typeof value === 'string' && value.trim() !== '' ? Number( value ) : value;
|
|
17
|
+
if ( typeof number !== 'number' || ! Number.isFinite( number ) ) {
|
|
18
|
+
throw new TypeError( `${ name } must be a finite number, got ${ String( value ) }.` );
|
|
19
|
+
}
|
|
20
|
+
if ( number < min ) {
|
|
21
|
+
throw new RangeError( `${ name } must be at least ${ min }, got ${ number }.` );
|
|
22
|
+
}
|
|
23
|
+
return number;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Converts a duration in years (fractions allowed) to whole months, at least 1.
|
|
28
|
+
*
|
|
29
|
+
* @param {*} years Duration in years.
|
|
30
|
+
* @return {number} Months.
|
|
31
|
+
*/
|
|
32
|
+
export function toMonths( years ) {
|
|
33
|
+
const months = Math.round( readNumber( 'years', years ) * 12 );
|
|
34
|
+
if ( months < 1 ) {
|
|
35
|
+
throw new RangeError( `years must be at least one month (1/12), got ${ years }.` );
|
|
36
|
+
}
|
|
37
|
+
return months;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Builds a chart series with one point per year (month 0, 12, 24...), plus
|
|
42
|
+
* the last month when the duration is not a whole number of years.
|
|
43
|
+
*
|
|
44
|
+
* @param {number} months Duration in months.
|
|
45
|
+
* @param {function(number): Object} point Values at a given month.
|
|
46
|
+
* @return {Array<Object>} Points: { year, month, ...point(month) }.
|
|
47
|
+
*/
|
|
48
|
+
export function yearlySeries( months, point ) {
|
|
49
|
+
const series = [];
|
|
50
|
+
for ( let month = 0; month < months; month += 12 ) {
|
|
51
|
+
series.push( { year: month / 12, month, ...point( month ) } );
|
|
52
|
+
}
|
|
53
|
+
series.push( { year: months / 12, month: months, ...point( months ) } );
|
|
54
|
+
return series;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Value of a monthly investment made at the start of each month
|
|
59
|
+
* (annuity due), after n months: P × ((1 + i)^n − 1) / i × (1 + i).
|
|
60
|
+
*
|
|
61
|
+
* @param {number} amount Monthly amount.
|
|
62
|
+
* @param {number} i Monthly rate (0.01 for 12% a year).
|
|
63
|
+
* @param {number} n Months.
|
|
64
|
+
* @return {number} Value.
|
|
65
|
+
*/
|
|
66
|
+
export function annuityDueValue( amount, i, n ) {
|
|
67
|
+
if ( i === 0 ) {
|
|
68
|
+
return amount * n;
|
|
69
|
+
}
|
|
70
|
+
return amount * ( ( Math.pow( 1 + i, n ) - 1 ) / i ) * ( 1 + i );
|
|
71
|
+
}
|