Created
February 10, 2017 23:30
-
-
Save gmmorris/0438291a9b31fdd223d44f2c88a5fc7e to your computer and use it in GitHub Desktop.
Roman Numerals converter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const romanNumeral = (char, val) => { | |
return { | |
char: char, | |
val: val, | |
isBellow: comp => comp > val, | |
isAbove: comp => comp < val, | |
is: comp => comp === val, | |
times: repeat => { | |
return (new Array(parseInt(repeat))).fill(char).join('') | |
} | |
} | |
} | |
const NUMERALS = [ | |
romanNumeral('I', 1), | |
romanNumeral('V', 5), | |
romanNumeral('X', 10), | |
romanNumeral('L', 50), | |
romanNumeral('C', 100), | |
romanNumeral('D', 500), | |
romanNumeral('M', 1000) | |
] | |
const lastItemInArray = arr => arr[arr.length - 1] | |
const LARGEST_NUMERAL = lastItemInArray(NUMERALS) | |
const extractDigits = numeric => { | |
let rem = 10 | |
let digits = 0 | |
while(digits == 0) { | |
digits = numeric % rem | |
rem *= 10 | |
} | |
return digits | |
} | |
const convert = numeric => { | |
const digitsToConvert = extractDigits(numeric) | |
const nextVal = numeric - digitsToConvert | |
let result = false | |
let indexOfNextNumeral = NUMERALS.findIndex(numeral => numeral.isAbove(digitsToConvert)) | |
if(indexOfNextNumeral === undefined) { | |
//above 1000 | |
return LARGEST_NUMERAL.times(LARGEST_NUMERAL.val/digitsToConvert) | |
} else { | |
const NEXT_NUMERAL = NUMERALS[indexOfNextNumeral] | |
let index = 0 | |
while(index < indexOfNextNumeral && !result) { | |
if(NUMERALS[index].val === digitsToConvert) | |
{ | |
result = NUMERALS[index].char | |
} else if(NEXT_NUMERAL.val - NUMERALS[index].val === digitsToConvert) { | |
result = NUMERALS[index].char + NEXT_NUMERAL.char | |
} else if(index + 1 === indexOfNextNumeral) { | |
if(index === 0) { | |
result = NUMERALS[index].times(digitsToConvert) | |
} else if(digitsToConvert % NUMERALS[index].val === 0) { | |
result = NUMERALS[index].times(digitsToConvert/NUMERALS[index].val) | |
} else { | |
result = NUMERALS[index].char + NUMERALS[index - 1].times(Math.abs(digitsToConvert - NUMERALS[index].val) / NUMERALS[index - 1].val) | |
} | |
} | |
index++ | |
} | |
} | |
return nextVal > 0 ? convert(nextVal) + result : result | |
} | |
console.log(convert(265)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment