From 84b3cd3d31e9aa9fd67c7746c5e011e12c0ddc81 Mon Sep 17 00:00:00 2001 From: Garrett Mills Date: Tue, 22 Jun 2021 01:15:42 +0000 Subject: [PATCH] Add 'finance.js' --- finance.js | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 finance.js diff --git a/finance.js b/finance.js new file mode 100644 index 0000000..bd7c954 --- /dev/null +++ b/finance.js @@ -0,0 +1,25 @@ +/** + * Calculate the # of periods to break-even on an initial investment, + * given some array of cash flows for as many periods. + * + * Returns -1 if never break even. + */ +function payback_period(initial, flows = []) { + let balance = -initial; + let periods = 0; + + for ( const flow of flows ) { + console.log({flow, balance, periods}) + if ( balance + flow > 0 ) { + periods += (Math.abs(balance)) / flow; + return periods; + } else { + balance += flow; + periods += 1; + } + } + + return -1; +} + +module.exports = exports = { payback_period } \ No newline at end of file