Skip to content

Commit 26edd9d

Browse files
Add return on investment algorithm to Maths
1 parent 5c39e87 commit 26edd9d

2 files changed

Lines changed: 62 additions & 0 deletions

File tree

Maths/ReturnOnInvestment.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* @function returnOnInvestment
3+
* @description Calculates Return on Investment (ROI) as a percentage.
4+
* ROI measures the profitability of an investment relative to its cost.
5+
* Formula: ROI = (Gain - Cost) / Cost * 100
6+
* @param {number} gainFromInvestment - Total value gained from the investment
7+
* @param {number} costOfInvestment - Total cost of the investment
8+
* @return {number} ROI as a percentage
9+
* @see https://www.investopedia.com/terms/r/returnoninvestment.asp
10+
* @example returnOnInvestment(1000, 500) = 100
11+
* @example returnOnInvestment(500, 500) = 0
12+
* @example returnOnInvestment(200, 500) = -60
13+
*/
14+
const returnOnInvestment = (gainFromInvestment, costOfInvestment) => {
15+
if (
16+
typeof gainFromInvestment !== 'number' ||
17+
typeof costOfInvestment !== 'number'
18+
) {
19+
throw new TypeError('Arguments must be numbers')
20+
}
21+
if (costOfInvestment <= 0) {
22+
throw new RangeError('costOfInvestment must be greater than 0')
23+
}
24+
return ((gainFromInvestment - costOfInvestment) / costOfInvestment) * 100
25+
}
26+
27+
export { returnOnInvestment }
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import { returnOnInvestment } from '../ReturnOnInvestment'
2+
3+
describe('returnOnInvestment', () => {
4+
test('positive ROI when gain exceeds cost', () => {
5+
expect(returnOnInvestment(1000, 500)).toBe(100)
6+
})
7+
8+
test('zero ROI when gain equals cost', () => {
9+
expect(returnOnInvestment(500, 500)).toBe(0)
10+
})
11+
12+
test('negative ROI when gain is less than cost', () => {
13+
expect(returnOnInvestment(200, 500)).toBe(-60)
14+
})
15+
16+
test('total loss when gain is zero', () => {
17+
expect(returnOnInvestment(0, 500)).toBe(-100)
18+
})
19+
20+
test('throws RangeError for zero cost', () => {
21+
expect(() => returnOnInvestment(1000, 0)).toThrow(RangeError)
22+
})
23+
24+
test('throws RangeError for negative cost', () => {
25+
expect(() => returnOnInvestment(1000, -100)).toThrow(RangeError)
26+
})
27+
28+
test('throws TypeError for non-number gain', () => {
29+
expect(() => returnOnInvestment('1000', 500)).toThrow(TypeError)
30+
})
31+
32+
test('throws TypeError for non-number cost', () => {
33+
expect(() => returnOnInvestment(1000, '500')).toThrow(TypeError)
34+
})
35+
})

0 commit comments

Comments
 (0)