I was trying to come up with a roman numerical generator in Javascript and I found this on Stack Overflow. I passes all tests but I cannot figure out how it works. I would really appreciate a nice description what is going on in this code:
let romanNumeralGenerator = (number) => {
return 'I'
.repeat(number)
.replace(/I{5}/g, 'V')
.replace(/V{2}/g, 'X')
.replace(/X{5}/g, 'L')
.replace(/L{2}/g, 'C')
.replace(/C{5}/g, 'D')
.replace(/D{2}/g, 'M')
.replace(/DC{4}/g, 'CM')
.replace(/C{4}/g, 'CD')
.replace(/LX{4}/g, 'XC')
.replace(/X{4}/g, 'XL')
.replace(/VI{4}/g, 'IX')
.replace(/I{4}/g, 'IV')
};
This is actually fairly simple to explain.
the method romanNumeralGenerator()
takes in a number as an argument, let's take the number 10
for example. The repeat()
method will repeat the string that it present the number of times specified, in our case 10 times. So when the number 10
is passed into our function it will repeat I
10 times creating the string IIIIIIIIII
.
Then the function takes the resulting string and performs the replace
method given the matching regular expression. In our case it will hit the first regex and see that we have at least 5 repeating I's
, so it will convert them into a V
giving us the string VIIIII
. It will recognize another string of 5 repeating I's
and convert them to a V
as well resulting in the string VV
. After that it will match the second regex and notice that there are 2 V's
present, which will convert the string to X
, giving us the correct roman numeral for the number 10
that we passed into the function. Hope this helps.