diff --git a/src/convertToRoman.js b/src/convertToRoman.js new file mode 100644 index 00000000..77dc58d4 --- /dev/null +++ b/src/convertToRoman.js @@ -0,0 +1,22 @@ +export default convertToRoman + +/** +*Original Source: https://stackoverflow.com/questions/9083037/convert-a-number-into-a-roman-numeral-in-javascript +*This method will convert a number into a roman numeral +* @param {Number} num - number to convert +* @return {String} - roman numeral of the number +*/ + +function convertToRoman(num) { + const arr1 = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] + const arr2 = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'] + let roman = '' + for (let i = 0; i < arr1.length; i++) { + if (num / arr1[i] >= 1) { + num = num - arr1[i] + roman = roman + arr2[i] + i-- + } + } + return roman +} diff --git a/src/index.js b/src/index.js index 63bcda0c..759c7fdf 100644 --- a/src/index.js +++ b/src/index.js @@ -41,6 +41,7 @@ import isOdd from './is-odd' import isNumeric from './is-numeric' import max from './max' import slugify from './slugify' +import convertToRoman from './convertToRoman' export { isOdd, @@ -86,4 +87,5 @@ export { isNumeric, max, slugify, + convertToRoman, } diff --git a/test/convertToRoman.test.js b/test/convertToRoman.test.js new file mode 100644 index 00000000..fbec0e42 --- /dev/null +++ b/test/convertToRoman.test.js @@ -0,0 +1,9 @@ +import test from 'ava' +import {convertToRoman} from '../src' + +test('convert to roman numeral', t => { + const object = 24 + const expected = 'XXIV' + const actual = convertToRoman(object) + t.deepEqual(actual, expected) +}) \ No newline at end of file