Skip to content

Instantly share code, notes, and snippets.

@scriptype
Last active December 22, 2021 21:28
Show Gist options
  • Save scriptype/5d945f70950e31c08490f8f25ff78ade to your computer and use it in GitHub Desktop.
Save scriptype/5d945f70950e31c08490f8f25ff78ade to your computer and use it in GitHub Desktop.
function save({
initialInvestment = 0,
baseMonthly,
contributionChangePercentageYearly,
contributionChangeFn,
returnPercentageYearly,
durationYears,
accumulatedExpense = 0,
accumulatedValue = 0,
values = [],
originalValues
}) {
if (!durationYears--) {
const formattedValues = values.map(row => {
return Object.keys(row).reduce((acc, column) => {
var cell = row[column]
return {
...acc,
[column]: typeof cell === 'number' ? cell.toLocaleString() : cell
}
}, {})
})
console.clear()
console.table(JSON.parse(JSON.stringify(originalValues)))
console.table(formattedValues)
return accumulatedValue
}
const newBaseMonthly = (
baseMonthly + (
contributionChangeFn
? contributionChangeFn(baseMonthly, (originalValues?.durationYears ?? 0) - durationYears)
: baseMonthly * contributionChangePercentageYearly/100
)
)
const newAccumulatedExpense = initialInvestment + accumulatedExpense + baseMonthly * 12
const baseAccumulatedValue = initialInvestment + accumulatedValue + baseMonthly * 12
const newAccumulatedValue = baseAccumulatedValue + baseAccumulatedValue * returnPercentageYearly/100
return save({
initialInvestment: 0,
baseMonthly: newBaseMonthly,
contributionChangePercentageYearly,
contributionChangeFn,
returnPercentageYearly,
durationYears,
accumulatedExpense: newAccumulatedExpense,
accumulatedValue: newAccumulatedValue,
values: values.concat({
'monthly invest': baseMonthly,
'accumulated expense': newAccumulatedExpense,
'accumulated value': newAccumulatedValue
}),
originalValues: originalValues || {
initialInvestment,
baseMonthly,
contributionChangePercentageYearly,
contributionChangeFn: contributionChangeFn.toString().replace(/^.+\{/, '').replace(/\n/g, '').replace(/\s+\}$/, '').replace(/^\s+/, ''),
returnPercentageYearly,
durationYears: durationYears + 1
}
})
}
save({
initialInvestment: 1000,
baseMonthly: 100,
contributionChangePercentageYearly: 5,
returnPercentageYearly: 5,
durationYears: 10
})
// or
save({
baseMonthly: 100,
contributionChangeFn(monthly, year) {
return year < 5 ? monthly * 33/100 : 0
},
returnPercentageYearly: 5,
durationYears: 10
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment