@wpgenius/financial-calculators 1.0.0 → 1.1.0

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