Add 'finance.js'
This commit is contained in:
parent
a964199ee4
commit
84b3cd3d31
25
finance.js
Normal file
25
finance.js
Normal file
@ -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 }
|
Loading…
Reference in New Issue
Block a user