@wpgenius/financial-calculators 1.0.1 → 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,4 @@
1
- /*! financial-calculators 1.0.1 | 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
2
  "use strict";
3
3
  var FinancialCalculators = (() => {
4
4
  var __defProp = Object.defineProperty;
@@ -56,12 +56,27 @@ var FinancialCalculators = (() => {
56
56
  }
57
57
  return months;
58
58
  }
59
- 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
+ };
60
75
  const series = [];
61
76
  for (let month = 0; month < months; month += 12) {
62
- series.push({ year: month / 12, month, ...point(month) });
77
+ series.push(at(month));
63
78
  }
64
- series.push({ year: months / 12, month: months, ...point(months) });
79
+ series.push(at(months));
65
80
  return series;
66
81
  }
67
82
  function annuityDueValue(amount, i, n) {
@@ -72,10 +87,11 @@ var FinancialCalculators = (() => {
72
87
  }
73
88
 
74
89
  // src/calculators/sip.js
75
- function sip({ monthlyAmount, annualRate, years }) {
90
+ function sip({ monthlyAmount, annualRate, years, startYear }) {
76
91
  const amount = readNumber("monthlyAmount", monthlyAmount);
77
92
  const i = readNumber("annualRate", annualRate) / 100 / 12;
78
93
  const months = toMonths(years);
94
+ const firstYear = readStartYear(startYear);
79
95
  const total = annuityDueValue(amount, i, months);
80
96
  const invested = amount * months;
81
97
  return {
@@ -86,15 +102,16 @@ var FinancialCalculators = (() => {
86
102
  series: yearlySeries(months, (month) => ({
87
103
  invested: amount * month,
88
104
  total: annuityDueValue(amount, i, month)
89
- }))
105
+ }), firstYear)
90
106
  };
91
107
  }
92
108
 
93
109
  // src/calculators/lumpsum.js
94
- function lumpsum({ amount, annualRate, years, compoundingPerYear = 1 }) {
110
+ function lumpsum({ amount, annualRate, years, compoundingPerYear = 1, startYear }) {
95
111
  const invested = readNumber("amount", amount);
96
112
  const rate = readNumber("annualRate", annualRate) / 100;
97
113
  const months = toMonths(years);
114
+ const firstYear = readStartYear(startYear);
98
115
  const k = readNumber("compoundingPerYear", compoundingPerYear, 1);
99
116
  const valueAt = (month) => invested * Math.pow(1 + rate / k, k * month / 12);
100
117
  const total = valueAt(months);
@@ -106,16 +123,17 @@ var FinancialCalculators = (() => {
106
123
  series: yearlySeries(months, (month) => ({
107
124
  invested,
108
125
  total: valueAt(month)
109
- }))
126
+ }), firstYear)
110
127
  };
111
128
  }
112
129
 
113
130
  // src/calculators/swp.js
114
- function swp({ investment, monthlyWithdrawal, annualRate, years }) {
131
+ function swp({ investment, monthlyWithdrawal, annualRate, years, startYear }) {
115
132
  const start = readNumber("investment", investment);
116
133
  const withdrawal = readNumber("monthlyWithdrawal", monthlyWithdrawal);
117
134
  const i = readNumber("annualRate", annualRate) / 100 / 12;
118
135
  const months = toMonths(years);
136
+ const firstYear = readStartYear(startYear);
119
137
  const balances = [start];
120
138
  const withdrawnTotals = [0];
121
139
  let balance = start;
@@ -146,17 +164,18 @@ var FinancialCalculators = (() => {
146
164
  series: yearlySeries(months, (month) => ({
147
165
  balance: balances[month],
148
166
  withdrawn: withdrawnTotals[month]
149
- }))
167
+ }), firstYear)
150
168
  };
151
169
  }
152
170
 
153
171
  // src/calculators/goal.js
154
- function goal({ presentCost, currentSavings = 0, inflationRate, annualRate, years }) {
172
+ function goal({ presentCost, currentSavings = 0, inflationRate, annualRate, years, startYear }) {
155
173
  const cost = readNumber("presentCost", presentCost);
156
174
  const savings = readNumber("currentSavings", currentSavings);
157
175
  const inflation = readNumber("inflationRate", inflationRate) / 100;
158
176
  const rate = readNumber("annualRate", annualRate) / 100;
159
177
  const months = toMonths(years);
178
+ const firstYear = readStartYear(startYear);
160
179
  const i = rate / 12;
161
180
  const costAt = (month) => cost * Math.pow(1 + inflation, month / 12);
162
181
  const savingsAt = (month) => savings * Math.pow(1 + rate, month / 12);
@@ -172,6 +191,7 @@ var FinancialCalculators = (() => {
172
191
  monthlyInvestment,
173
192
  totalInvested: monthlyInvestment * months,
174
193
  months,
194
+ ...firstYear === void 0 ? {} : { targetYear: firstYear + months / 12 },
175
195
  series: yearlySeries(months, (month) => {
176
196
  const investments = annuityDueValue(monthlyInvestment, i, month);
177
197
  return {
@@ -180,15 +200,16 @@ var FinancialCalculators = (() => {
180
200
  investments,
181
201
  total: savingsAt(month) + investments
182
202
  };
183
- })
203
+ }, firstYear)
184
204
  };
185
205
  }
186
206
 
187
207
  // src/calculators/emi.js
188
- function emi({ principal, annualRate, years }) {
208
+ function emi({ principal, annualRate, years, startYear }) {
189
209
  const loan = readNumber("principal", principal);
190
210
  const i = readNumber("annualRate", annualRate) / 100 / 12;
191
211
  const months = toMonths(years);
212
+ const firstYear = readStartYear(startYear);
192
213
  const instalment = i === 0 ? loan / months : loan * i * Math.pow(1 + i, months) / (Math.pow(1 + i, months) - 1);
193
214
  const balances = [loan];
194
215
  const principalPaid = [0];
@@ -224,7 +245,7 @@ var FinancialCalculators = (() => {
224
245
  balance: balances[month],
225
246
  principalPaid: principalPaid[month],
226
247
  interestPaid: interestPaid[month]
227
- }))
248
+ }), firstYear)
228
249
  };
229
250
  }
230
251
 
@@ -250,6 +271,20 @@ var FinancialCalculators = (() => {
250
271
  var LOCALES = { indian: "en-IN", international: "en-US" };
251
272
  var intlChecked = false;
252
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
+ }
253
288
  function canUseIntl() {
254
289
  if (!intlChecked) {
255
290
  intlChecked = true;
@@ -298,11 +333,7 @@ var FinancialCalculators = (() => {
298
333
  const rounded = Number(value.toFixed(decimals));
299
334
  const number = rounded === 0 ? 0 : value;
300
335
  if (canUseIntl()) {
301
- return new Intl.NumberFormat(LOCALES[system], {
302
- minimumFractionDigits: decimals,
303
- maximumFractionDigits: decimals,
304
- useGrouping: true
305
- }).format(number);
336
+ return formatter(system, decimals).format(number);
306
337
  }
307
338
  return formatByHand(number, decimals, system);
308
339
  }
@@ -335,103 +366,157 @@ var FinancialCalculators = (() => {
335
366
  }
336
367
 
337
368
  // src/format/words.js
338
- var ONES = [
339
- "",
340
- "One",
341
- "Two",
342
- "Three",
343
- "Four",
344
- "Five",
345
- "Six",
346
- "Seven",
347
- "Eight",
348
- "Nine",
349
- "Ten",
350
- "Eleven",
351
- "Twelve",
352
- "Thirteen",
353
- "Fourteen",
354
- "Fifteen",
355
- "Sixteen",
356
- "Seventeen",
357
- "Eighteen",
358
- "Nineteen"
359
- ];
360
- var TENS = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"];
361
- var INTERNATIONAL_SCALES = [
362
- "",
363
- "Thousand",
364
- "Million",
365
- "Billion",
366
- "Trillion",
367
- "Quadrillion",
368
- "Quintillion",
369
- "Sextillion",
370
- "Septillion",
371
- "Octillion",
372
- "Nonillion",
373
- "Decillion"
374
- ];
375
- function belowHundred(n) {
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) {
376
462
  if (n < 20) {
377
- return ONES[n];
463
+ return w.ones[n];
378
464
  }
379
- 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]]);
380
466
  }
381
- function belowThousand(n) {
467
+ function belowThousand(n, w) {
382
468
  const hundreds = Math.floor(n / 100);
383
469
  const rest = n % 100;
384
470
  if (!hundreds) {
385
- return belowHundred(rest);
471
+ return belowHundred(rest, w);
386
472
  }
387
- return `${ONES[hundreds]} Hundred` + (rest ? ` and ${belowHundred(rest)}` : "");
388
- }
389
- function join(parts) {
390
- return parts.filter(Boolean).join(" ");
473
+ return join([w.ones[hundreds], w.hundred, rest ? w.and : "", rest ? belowHundred(rest, w) : ""]);
391
474
  }
392
- function indian(digits) {
475
+ function indian(digits, w) {
393
476
  digits = digits.replace(/^0+/, "");
394
477
  if (digits === "") {
395
478
  return "";
396
479
  }
397
480
  if (digits.length > 7) {
398
- const crores = indian(digits.slice(0, -7));
399
- 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)]);
400
483
  }
401
484
  const n = Number(digits);
402
485
  const lakh = Math.floor(n / 1e5);
403
486
  const thousand = Math.floor(n % 1e5 / 1e3);
404
487
  const rest = n % 1e3;
405
488
  return join([
406
- lakh && `${belowHundred(lakh)} Lakh`,
407
- thousand && `${belowHundred(thousand)} Thousand`,
408
- belowThousand(rest)
489
+ lakh && `${belowHundred(lakh, w)} ${w.indian.lakh}`,
490
+ thousand && `${belowHundred(thousand, w)} ${w.indian.thousand}`,
491
+ belowThousand(rest, w)
409
492
  ]);
410
493
  }
411
- function international(digits) {
494
+ function international(digits, w) {
412
495
  digits = digits.replace(/^0+/, "");
413
496
  if (digits === "") {
414
497
  return "";
415
498
  }
416
- const maxDigits = INTERNATIONAL_SCALES.length * 3;
499
+ const scales = w.international;
500
+ const maxDigits = scales.length * 3;
417
501
  if (digits.length > maxDigits) {
418
- const top = international(digits.slice(0, -(maxDigits - 3)));
419
- const last = INTERNATIONAL_SCALES[INTERNATIONAL_SCALES.length - 1];
420
- return join([top && `${top} ${last}`, international(digits.slice(-(maxDigits - 3)))]);
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)]);
421
505
  }
422
506
  const parts = [];
423
507
  for (let end = digits.length, scale = 0; end > 0; end -= 3, scale++) {
424
508
  const group = Number(digits.slice(Math.max(0, end - 3), end));
425
509
  if (group) {
426
- parts.unshift(join([belowThousand(group), INTERNATIONAL_SCALES[scale]]));
510
+ parts.unshift(join([belowThousand(group, w), scales[scale]]));
427
511
  }
428
512
  }
429
513
  return join(parts);
430
514
  }
431
- function amountInWords(value, { system = "indian" } = {}) {
515
+ function amountInWords(value, { system = "indian", words } = {}) {
432
516
  if (system !== "indian" && system !== "international") {
433
517
  throw new RangeError(`system must be "indian" or "international", got "${system}".`);
434
518
  }
519
+ const w = readWords(words);
435
520
  let digits;
436
521
  let negative = false;
437
522
  if (typeof value === "number") {
@@ -451,14 +536,14 @@ var FinancialCalculators = (() => {
451
536
  } else {
452
537
  throw new TypeError(`value must be a number, a BigInt or a string of digits, got ${String(value)}.`);
453
538
  }
454
- const words = system === "indian" ? indian(digits) : international(digits);
455
- if (words === "") {
456
- return "Zero";
539
+ const text = system === "indian" ? indian(digits, w) : international(digits, w);
540
+ if (text === "") {
541
+ return w.zero;
457
542
  }
458
- return negative ? `Minus ${words}` : words;
543
+ return negative ? join([w.minus, text]) : text;
459
544
  }
460
545
 
461
546
  // src/index.js
462
- var VERSION = true ? "1.0.1" : "development";
547
+ var VERSION = true ? "1.1.0" : "development";
463
548
  return __toCommonJS(index_exports);
464
549
  })();
@@ -1,2 +1,2 @@
1
- /*! financial-calculators 1.0.1 | GPL-3.0-or-later | https://wpgenius.github.io/financial-calculators-js/ */
2
- "use strict";var FinancialCalculators=(()=>{var P=Object.defineProperty;var Z=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var J=Object.prototype.hasOwnProperty;var X=(t,n)=>{for(var r in n)P(t,r,{get:n[r],enumerable:!0})},tt=(t,n,r,e)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of q(n))!J.call(t,o)&&o!==r&&P(t,o,{get:()=>n[o],enumerable:!(e=Z(n,o))||e.enumerable});return t};var nt=t=>tt(P({},"__esModule",{value:!0}),t);var at={};X(at,{VERSION:()=>st,amountInWords:()=>Y,calculate:()=>L,emi:()=>I,formatCompact:()=>Q,formatCurrency:()=>K,formatNumber:()=>x,goal:()=>T,groupDigits:()=>B,lumpsum:()=>M,register:()=>U,sip:()=>S,swp:()=>E,types:()=>A});function f(t,n,r=0){let e=typeof n=="string"&&n.trim()!==""?Number(n):n;if(typeof e!="number"||!Number.isFinite(e))throw new TypeError(`${t} must be a finite number, got ${String(n)}.`);if(e<r)throw new RangeError(`${t} must be at least ${r}, got ${e}.`);return e}function d(t){let n=Math.round(f("years",t)*12);if(n<1)throw new RangeError(`years must be at least one month (1/12), got ${t}.`);return n}function g(t,n){let r=[];for(let e=0;e<t;e+=12)r.push({year:e/12,month:e,...n(e)});return r.push({year:t/12,month:t,...n(t)}),r}function y(t,n,r){return n===0?t*r:t*((Math.pow(1+n,r)-1)/n)*(1+n)}function S({monthlyAmount:t,annualRate:n,years:r}){let e=f("monthlyAmount",t),o=f("annualRate",n)/100/12,i=d(r),c=y(e,o,i),u=e*i;return{invested:u,returns:c-u,total:c,months:i,series:g(i,l=>({invested:e*l,total:y(e,o,l)}))}}function M({amount:t,annualRate:n,years:r,compoundingPerYear:e=1}){let o=f("amount",t),i=f("annualRate",n)/100,c=d(r),u=f("compoundingPerYear",e,1),l=a=>o*Math.pow(1+i/u,u*a/12),m=l(c);return{invested:o,returns:m-o,total:m,months:c,series:g(c,a=>({invested:o,total:l(a)}))}}function E({investment:t,monthlyWithdrawal:n,annualRate:r,years:e}){let o=f("investment",t),i=f("monthlyWithdrawal",n),c=f("annualRate",r)/100/12,u=d(e),l=[o],m=[0],a=o,h=0,b=null;for(let s=1;s<=u;s++){let p=Math.min(i,a);a-=p,h+=p,a<=0?(a=0,b===null&&i>0&&(b=s)):a+=a*c,l.push(a),m.push(h)}return{investment:o,totalWithdrawn:h,finalBalance:a,returns:a+h-o,depletedMonth:b,months:u,series:g(u,s=>({balance:l[s],withdrawn:m[s]}))}}function T({presentCost:t,currentSavings:n=0,inflationRate:r,annualRate:e,years:o}){let i=f("presentCost",t),c=f("currentSavings",n),u=f("inflationRate",r)/100,l=f("annualRate",e)/100,m=d(o),a=l/12,h=w=>i*Math.pow(1+u,w/12),b=w=>c*Math.pow(1+l,w/12),s=h(m),p=b(m),N=Math.max(0,s-p),O=N/y(1,a,m);return{presentCost:i,futureCost:s,savingsFutureValue:p,shortfall:N,monthlyInvestment:O,totalInvested:O*m,months:m,series:g(m,w=>{let W=y(O,a,w);return{goalCost:h(w),savings:b(w),investments:W,total:b(w)+W}})}}function I({principal:t,annualRate:n,years:r}){let e=f("principal",t),o=f("annualRate",n)/100/12,i=d(r),c=o===0?e/i:e*o*Math.pow(1+o,i)/(Math.pow(1+o,i)-1),u=[e],l=[0],m=[0],a=e;for(let s=1;s<=i;s++){let p=a*o,N=s===i?a:c-p;a=Math.max(0,a-N),u.push(a),l.push(l[s-1]+N),m.push(m[s-1]+p)}let h=[];for(let s=0;s<i;s+=12){let p=Math.min(s+12,i);h.push({year:h.length+1,principalPaid:l[p]-l[s],interestPaid:m[p]-m[s],balance:u[p]})}let b=c*i;return{emi:c,principal:e,totalInterest:b-e,totalPayment:b,months:i,schedule:h,series:g(i,s=>({balance:u[s],principalPaid:l[s],interestPaid:m[s]}))}}var F={sip:S,lumpsum:M,swp:E,goal:T,emi:I};function A(){return Object.keys(F)}function L(t,n){if(!Object.prototype.hasOwnProperty.call(F,t))throw new Error(`Unknown calculator "${t}". Available: ${A().join(", ")}.`);return F[t](n)}function U(t,n){if(typeof t!="string"||t===""||typeof n!="function")throw new TypeError("register( type, fn ) needs a type name and a function.");F[t]=n}var v={indian:"en-IN",international:"en-US"},H=!1,D=!1;function et(){if(!H){H=!0;try{D=new Intl.NumberFormat("en-IN").format(1234567)==="12,34,567"&&new Intl.NumberFormat("en-US").format(1234567)==="1,234,567"}catch{D=!1}}return D}function _(t){if(!Object.prototype.hasOwnProperty.call(v,t))throw new RangeError(`system must be "indian" or "international", got "${t}".`);return t}function z(t){if(!Number.isInteger(t)||t<0||t>20)throw new RangeError(`decimals must be a whole number from 0 to 20, got ${t}.`);return t}function B(t,n="indian"){if(t.length<=3)return t;let r=t.slice(-3),e=t.slice(0,-3),o=_(n)==="indian"?2:3,i=new RegExp(`\\B(?=(\\d{${o}})+(?!\\d))`,"g");return e.replace(i,",")+","+r}function rt(t,n,r){let e=Math.abs(t).toFixed(n),[o,i]=e.split(".");return(t<0&&Number(e)!==0?"-":"")+B(o,r)+(i?"."+i:"")}function x(t,{system:n="indian",decimals:r=0}={}){if(_(n),z(r),typeof t!="number"||!Number.isFinite(t))throw new TypeError(`value must be a finite number, got ${String(t)}.`);let o=Number(t.toFixed(r))===0?0:t;return et()?new Intl.NumberFormat(v[n],{minimumFractionDigits:r,maximumFractionDigits:r,useGrouping:!0}).format(o):rt(o,r,n)}function K(t,{symbol:n="\u20B9",position:r="before",system:e="indian",decimals:o=0}={}){let i=x(t,{system:e,decimals:o}),c=i.startsWith("-"),u=c?i.slice(1):i,l=c?"-":"";return r==="after"?`${l}${u} ${n}`:`${l}${n}${u}`}var ot={indian:[[1e7,"Cr"],[1e5,"L"],[1e3,"K"]],international:[[1e12,"T"],[1e9,"B"],[1e6,"M"],[1e3,"K"]]};function Q(t,{system:n="indian",decimals:r=1}={}){if(_(n),z(r),typeof t!="number"||!Number.isFinite(t))throw new TypeError(`value must be a finite number, got ${String(t)}.`);let e=Math.abs(t),o=t<0?"-":"";for(let[i,c]of ot[n])if(e>=i){let u=Number((e/i).toFixed(r));return`${o}${x(u,{system:n,decimals:u%1===0?0:r})}${c}`}return x(t,{system:n,decimals:0})}var k=["","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"],it=["","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"],R=["","Thousand","Million","Billion","Trillion","Quadrillion","Quintillion","Sextillion","Septillion","Octillion","Nonillion","Decillion"];function C(t){return t<20?k[t]:[it[Math.floor(t/10)],k[t%10]].filter(Boolean).join(" ")}function G(t){let n=Math.floor(t/100),r=t%100;return n?`${k[n]} Hundred`+(r?` and ${C(r)}`:""):C(r)}function $(t){return t.filter(Boolean).join(" ")}function j(t){if(t=t.replace(/^0+/,""),t==="")return"";if(t.length>7){let i=j(t.slice(0,-7));return $([i&&`${i} Crore`,j(t.slice(-7))])}let n=Number(t),r=Math.floor(n/1e5),e=Math.floor(n%1e5/1e3),o=n%1e3;return $([r&&`${C(r)} Lakh`,e&&`${C(e)} Thousand`,G(o)])}function V(t){if(t=t.replace(/^0+/,""),t==="")return"";let n=R.length*3;if(t.length>n){let e=V(t.slice(0,-(n-3))),o=R[R.length-1];return $([e&&`${e} ${o}`,V(t.slice(-(n-3)))])}let r=[];for(let e=t.length,o=0;e>0;e-=3,o++){let i=Number(t.slice(Math.max(0,e-3),e));i&&r.unshift($([G(i),R[o]]))}return $(r)}function Y(t,{system:n="indian"}={}){if(n!=="indian"&&n!=="international")throw new RangeError(`system must be "indian" or "international", got "${n}".`);let r,e=!1;if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`value must be a finite number, got ${t}.`);let i=Math.round(Math.abs(t));e=t<0&&i!==0,r=BigInt(i).toString()}else if(typeof t=="bigint")e=t<0n,r=(e?-t:t).toString();else if(typeof t=="string"&&/^-?\d+$/.test(t.trim())){let i=t.trim();e=i.startsWith("-")&&/[1-9]/.test(i),r=i.replace("-","")}else throw new TypeError(`value must be a number, a BigInt or a string of digits, got ${String(t)}.`);let o=n==="indian"?j(r):V(r);return o===""?"Zero":e?`Minus ${o}`:o}var st="1.0.1";return nt(at);})();
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.1",
3
+ "version": "1.1.0",
4
4
  "description": "Financial calculators in plain JavaScript with no dependencies: SIP, lump sum, SWP, goal and EMI, Indian and international number formatting, and amounts in words.",
5
5
  "keywords": [
6
6
  "finance",
@@ -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
  }