UNPKG

@mcnoble/interest

Version:

A simple interest and compound interest calculator

56 lines (41 loc) 1.51 kB
function simpleInterest(principal, rate, time, timeUnit = 'years') { if (principal <= 0 || rate <= 0 || time <= 0) { throw new Error('Principal, rate, and time must be positive values.'); } const timeInYears = convertToYears(time, timeUnit); return (principal * rate * timeInYears) / 100; } function convertToYears(time, timeUnit) { const unitMap = { years: 1, months: 1 / 12, days: 1 / 365 }; if (!unitMap[timeUnit]) { throw new Error('Invalid time unit. Use "years", "months", or "days".'); } return time * unitMap[timeUnit]; } function compoundInterest(principal, rate, time, frequency = 'annually') { if (principal <= 0 || rate <= 0 || time <= 0) { throw new Error('Principal, rate, and time must be positive values.'); } const n = getCompoundingFrequency(frequency); const compoundAmount = principal * Math.pow(1 + (rate / (100 * n)), n * time); return parseFloat((compoundAmount - principal).toFixed(2)); } function getCompoundingFrequency(frequency) { const frequencyMap = { annually: 1, yearly: 1, semiannually: 2, quarterly: 4, monthly: 12, daily: 365 }; if (!frequencyMap[frequency]) { throw new Error('Invalid frequency. Use "annually", "yearly", "semiannually", "quarterly", "monthly", or "daily".'); } return frequencyMap[frequency]; } export { simpleInterest, compoundInterest };