Created
May 12, 2022 15:22
-
-
Save thedom85/0ca1d5ddf82e7b59cecec4ed6684f7b3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// https://www.codewars.com/kata/51b66044bce5799a7f000003/train/javascript | |
const values = {M: 1000,CM: 900, D: 500,CD: 400,C: 100,XC: 90, L: 50, XL: 40,X: 10,IX: 9,V: 5,IV: 4,I: 1 } | |
const orders = ['M','CM','D','CD','C','XC','L','XL','X','IX','V','IV','I']; | |
function RomanNumerals(){}; | |
RomanNumerals.toRoman = function(num) { | |
let roman = '' | |
for (const symbol of orders) { | |
while (num >= values[symbol]) { | |
roman += symbol | |
num -= values[symbol] | |
} | |
} | |
return roman | |
}; | |
RomanNumerals.fromRoman = function(romanNumber) { | |
let prev = ' ' | |
let sum = 0 | |
let newPrev = 0 | |
for (let i = romanNumber.length - 1; i >= 0; i--) { | |
const c = romanNumber.charAt(i) | |
if (prev !== ' ') { | |
newPrev = values[prev] > newPrev ? values[prev] : newPrev | |
} | |
const currentNum = values[c] | |
if (currentNum >= newPrev) { | |
sum += currentNum | |
} else { | |
sum -= currentNum | |
} | |
prev = c | |
} | |
return sum | |
}; | |
console.log(RomanNumerals.toRoman(1000), 'M'); | |
console.log(RomanNumerals.toRoman(4), 'IV'); | |
console.log(RomanNumerals.toRoman(1), 'I'); | |
console.log(RomanNumerals.toRoman(1990), 'MCMXC'); | |
console.log(RomanNumerals.toRoman(2008), 'MMVIII'); | |
console.log(RomanNumerals.fromRoman('XXI'), 21); | |
console.log(RomanNumerals.fromRoman('I'), 1); | |
console.log(RomanNumerals.fromRoman('IV'), 4); | |
console.log(RomanNumerals.fromRoman('MMVIII'), 2008); | |
console.log(RomanNumerals.fromRoman('MDCLXVI'), 1666); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment