JSFiddle - React, Tailwind, and code Playground
HTML
<input id="cardinalToRoman" type="number" placeholder="Cardinal to roman" /> <button onClick="convertToRoman()">Convert to roman</button>
<div id="cardinalToRomanResult"></div>
<br />
<input id="romanToCardinal" type="text" placeholder="Roman to cardinal" /> <button onClick="convertToCardinal()">Convert to cardinal</button>
<div id="romanToCardinalResult"></div>
<script>
function convertToRoman() {
document.getElementById('cardinalToRomanResult').innerHTML = cardinalToRoman(document.getElementById('cardinalToRoman').value);
}
function convertToCardinal() {
document.getElementById('romanToCardinalResult').innerHTML = romanToCardinal(document.getElementById('romanToCardinal').value);
}
</script>
JavaScript
const _numbersMap = {
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
}
// The funciton receives a cardinal as parameter (of integer type)
const cardinalToRoman = num => {
// M is the last char in the roman numeric system. Just preventing crashes.
if (num >= 4000) {
console.log('Number is too big');
return
}
let roman = ''; // The initial roman string
// It iterates over the _numbersMap object's properties
for (var i of Object.keys(_numbersMap)) {
/* For each iteration, it will calculate the division of the
given number by the value of the property beeing iterated. */
var q = Math.floor(num / _numbersMap[i]);
/* So the value, multiplied by the current property's value,
will be subtracted from the given number */
num -= q * _numbersMap[i];
/* The result will be the times that the key of the
current property (its respective roman sting) will be repeated
in the final string */
roman += i.repeat(q);
}
return roman;
};
// The funciton receives a roman number as parameter (of srting type)
const romanToCardinal = roman => {
let num = 0; // Initial integer number
/* Let's split the roman string in a Array of chars, and then
put it in reverse order */
const romansArray = Array.from(roman).reverse();
// Then let's iterate the array
romansArray.forEach((char, index, array) => {
/* We take the integer number corresponding to the current
and the previous chars in the iteration. */
const currentNumChar = _numbersMap[char];
const prevNumChar = _numbersMap[array[index - 1]];
// Throws error if the char is unknown.
if (!currentNumChar) {
console.error(`The charecter "${char}" of the given roman number "${roman}" is invalid as a roman number char.`);
...