Skip to content

Commit 7497a62

Browse files
feat: add Roman numeral to number conversion
1 parent 5c39e87 commit 7497a62

2 files changed

Lines changed: 84 additions & 0 deletions

File tree

‎Conversions/RomanToNumber.js‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* @function romanToNumber
3+
* @description Converts a Roman numeral string to its decimal number.
4+
* @param {string} roman - A valid Roman numeral string
5+
* @returns {number} - The decimal representation of the Roman numeral
6+
* @see https://en.wikipedia.org/wiki/Roman_numerals
7+
* @example romanToNumber("III") => 3
8+
* @example romanToNumber("IX") => 9
9+
* @example romanToNumber("MCMXCIV") => 1994
10+
*/
11+
const romanToNumber = (roman) => {
12+
if (typeof roman !== 'string' || !/^[IVXLCDM]+$/.test(roman)) {
13+
throw new TypeError('Input must be a valid Roman numeral string')
14+
}
15+
const romanValues = {
16+
I: 1,
17+
V: 5,
18+
X: 10,
19+
L: 50,
20+
C: 100,
21+
D: 500,
22+
M: 1000
23+
}
24+
let result = 0
25+
for (let i = 0; i < roman.length; i++) {
26+
const current = romanValues[roman[i]]
27+
const next = romanValues[roman[i + 1]]
28+
if (next && current < next) {
29+
result -= current
30+
} else {
31+
result += current
32+
}
33+
}
34+
return result
35+
}
36+
37+
export { romanToNumber }
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { romanToNumber } from '../RomanToNumber.js'
2+
3+
describe('romanToNumber', () => {
4+
test("romanToNumber('I') returns 1", () => {
5+
expect(romanToNumber('I')).toBe(1)
6+
})
7+
8+
test("romanToNumber('III') returns 3", () => {
9+
expect(romanToNumber('III')).toBe(3)
10+
})
11+
12+
test("romanToNumber('IV') returns 4", () => {
13+
expect(romanToNumber('IV')).toBe(4)
14+
})
15+
16+
test("romanToNumber('IX') returns 9", () => {
17+
expect(romanToNumber('IX')).toBe(9)
18+
})
19+
20+
test("romanToNumber('LVIII') returns 58", () => {
21+
expect(romanToNumber('LVIII')).toBe(58)
22+
})
23+
24+
test("romanToNumber('MCMXCIV') returns 1994", () => {
25+
expect(romanToNumber('MCMXCIV')).toBe(1994)
26+
})
27+
28+
test("romanToNumber('MMMCMXCIX') returns 3999", () => {
29+
expect(romanToNumber('MMMCMXCIX')).toBe(3999)
30+
})
31+
32+
test("romanToNumber('XL') returns 40", () => {
33+
expect(romanToNumber('XL')).toBe(40)
34+
})
35+
36+
test('throws TypeError for empty string', () => {
37+
expect(() => romanToNumber('')).toThrow(TypeError)
38+
})
39+
40+
test('throws TypeError for invalid characters', () => {
41+
expect(() => romanToNumber('ABC')).toThrow(TypeError)
42+
})
43+
44+
test('throws TypeError for non-string input', () => {
45+
expect(() => romanToNumber(10)).toThrow(TypeError)
46+
})
47+
})

0 commit comments

Comments
 (0)