Skip to content

Commit 6b653ce

Browse files
Add return on investment to math algorithms
1 parent 3b53377 commit 6b653ce

3 files changed

Lines changed: 61 additions & 0 deletions

File tree

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Return on Investment (ROI)
2+
3+
Return on Investment (ROI) is a financial metric that measures the profitability
4+
of an investment relative to its cost. It is expressed as a percentage.
5+
6+
## Formula
7+
8+
```
9+
ROI = (Gain from Investment - Cost of Investment) / Cost of Investment × 100
10+
```
11+
12+
## Examples
13+
14+
| Gain | Cost | ROI |
15+
|--------|-------|---------|
16+
| $1000 | $500 | 100% |
17+
| $500 | $500 | 0% |
18+
| $200 | $500 | -60% |
19+
| $0 | $500 | -100% |
20+
21+
## References
22+
23+
- [Investopedia - Return on Investment](https://www.investopedia.com/terms/r/returnoninvestment.asp)
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
/**
2+
* @param {number} gainFromInvestment
3+
* @param {number} costOfInvestment
4+
* @return {number}
5+
*/
6+
export default function returnOnInvestment(gainFromInvestment, costOfInvestment) {
7+
if (costOfInvestment <= 0) {
8+
throw new Error('costOfInvestment must be greater than 0');
9+
}
10+
return ((gainFromInvestment - costOfInvestment) / costOfInvestment) * 100;
11+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import returnOnInvestment from '../ReturnOnInvestment';
2+
3+
describe('returnOnInvestment', () => {
4+
it('should calculate positive ROI', () => {
5+
expect(returnOnInvestment(1000, 500)).toBe(100);
6+
});
7+
8+
it('should return zero ROI when gain equals cost', () => {
9+
expect(returnOnInvestment(500, 500)).toBe(0);
10+
});
11+
12+
it('should calculate negative ROI', () => {
13+
expect(returnOnInvestment(200, 500)).toBe(-60);
14+
});
15+
16+
it('should return -100 for total loss', () => {
17+
expect(returnOnInvestment(0, 500)).toBe(-100);
18+
});
19+
20+
it('should throw on zero cost', () => {
21+
expect(() => returnOnInvestment(1000, 0)).toThrow();
22+
});
23+
24+
it('should throw on negative cost', () => {
25+
expect(() => returnOnInvestment(1000, -100)).toThrow();
26+
});
27+
});

0 commit comments

Comments
 (0)