Skip to content

Commit 5d03910

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

2 files changed

Lines changed: 90 additions & 0 deletions

File tree

‎Conversions/NumberToRoman.js‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* @function numberToRoman
3+
* @description Converts a decimal number to its Roman numeral representation.
4+
* @param {number} num - A positive integer between 1 and 3999
5+
* @returns {string} - The Roman numeral representation
6+
* @see https://en.wikipedia.org/wiki/Roman_numerals
7+
* @example numberToRoman(3) => "III"
8+
* @example numberToRoman(9) => "IX"
9+
* @example numberToRoman(58) => "LVIII"
10+
* @example numberToRoman(1994) => "MCMXCIV"
11+
*/
12+
const numberToRoman = (num) => {
13+
if (!Number.isInteger(num) || num < 1 || num > 3999) {
14+
throw new TypeError('Input must be an integer between 1 and 3999')
15+
}
16+
const values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
17+
const symbols = [
18+
'M',
19+
'CM',
20+
'D',
21+
'CD',
22+
'C',
23+
'XC',
24+
'L',
25+
'XL',
26+
'X',
27+
'IX',
28+
'V',
29+
'IV',
30+
'I'
31+
]
32+
let result = ''
33+
let remaining = num
34+
for (let i = 0; i < values.length; i++) {
35+
while (remaining >= values[i]) {
36+
result += symbols[i]
37+
remaining -= values[i]
38+
}
39+
}
40+
return result
41+
}
42+
43+
export { numberToRoman }
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { numberToRoman } from '../NumberToRoman.js'
2+
3+
describe('numberToRoman', () => {
4+
test("numberToRoman(1) returns 'I'", () => {
5+
expect(numberToRoman(1)).toBe('I')
6+
})
7+
8+
test("numberToRoman(3) returns 'III'", () => {
9+
expect(numberToRoman(3)).toBe('III')
10+
})
11+
12+
test("numberToRoman(4) returns 'IV'", () => {
13+
expect(numberToRoman(4)).toBe('IV')
14+
})
15+
16+
test("numberToRoman(9) returns 'IX'", () => {
17+
expect(numberToRoman(9)).toBe('IX')
18+
})
19+
20+
test("numberToRoman(40) returns 'XL'", () => {
21+
expect(numberToRoman(40)).toBe('XL')
22+
})
23+
24+
test("numberToRoman(58) returns 'LVIII'", () => {
25+
expect(numberToRoman(58)).toBe('LVIII')
26+
})
27+
28+
test("numberToRoman(1994) returns 'MCMXCIV'", () => {
29+
expect(numberToRoman(1994)).toBe('MCMXCIV')
30+
})
31+
32+
test("numberToRoman(3999) returns 'MMMCMXCIX'", () => {
33+
expect(numberToRoman(3999)).toBe('MMMCMXCIX')
34+
})
35+
36+
test('throws TypeError for 0', () => {
37+
expect(() => numberToRoman(0)).toThrow(TypeError)
38+
})
39+
40+
test('throws TypeError for 4000', () => {
41+
expect(() => numberToRoman(4000)).toThrow(TypeError)
42+
})
43+
44+
test('throws TypeError for float', () => {
45+
expect(() => numberToRoman(1.5)).toThrow(TypeError)
46+
})
47+
})

0 commit comments

Comments
 (0)