Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions Conversions/NumberToRoman.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
* @function numberToRoman
* @description Converts a decimal number to its Roman numeral representation.
* @param {number} num - A positive integer between 1 and 3999
* @returns {string} - The Roman numeral representation
* @see https://en.wikipedia.org/wiki/Roman_numerals
* @example numberToRoman(3) => "III"
* @example numberToRoman(9) => "IX"
* @example numberToRoman(58) => "LVIII"
* @example numberToRoman(1994) => "MCMXCIV"
*/
const numberToRoman = (num) => {
if (!Number.isInteger(num) || num < 1 || num > 3999) {
throw new TypeError('Input must be an integer between 1 and 3999')
}
const values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
const symbols = [
'M',
'CM',
'D',
'CD',
'C',
'XC',
'L',
'XL',
'X',
'IX',
'V',
'IV',
'I'
]
let result = ''
let remaining = num
for (let i = 0; i < values.length; i++) {
while (remaining >= values[i]) {
result += symbols[i]
remaining -= values[i]
}
}
return result
}

export { numberToRoman }
47 changes: 47 additions & 0 deletions Conversions/test/NumberToRoman.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { numberToRoman } from '../NumberToRoman.js'

describe('numberToRoman', () => {
test("numberToRoman(1) returns 'I'", () => {
expect(numberToRoman(1)).toBe('I')
})

test("numberToRoman(3) returns 'III'", () => {
expect(numberToRoman(3)).toBe('III')
})

test("numberToRoman(4) returns 'IV'", () => {
expect(numberToRoman(4)).toBe('IV')
})

test("numberToRoman(9) returns 'IX'", () => {
expect(numberToRoman(9)).toBe('IX')
})

test("numberToRoman(40) returns 'XL'", () => {
expect(numberToRoman(40)).toBe('XL')
})

test("numberToRoman(58) returns 'LVIII'", () => {
expect(numberToRoman(58)).toBe('LVIII')
})

test("numberToRoman(1994) returns 'MCMXCIV'", () => {
expect(numberToRoman(1994)).toBe('MCMXCIV')
})

test("numberToRoman(3999) returns 'MMMCMXCIX'", () => {
expect(numberToRoman(3999)).toBe('MMMCMXCIX')
})

test('throws TypeError for 0', () => {
expect(() => numberToRoman(0)).toThrow(TypeError)
})

test('throws TypeError for 4000', () => {
expect(() => numberToRoman(4000)).toThrow(TypeError)
})

test('throws TypeError for float', () => {
expect(() => numberToRoman(1.5)).toThrow(TypeError)
})
})
Loading