My question might be confusing, but I’ll try to be as clear as possible.
So I am stuck with the “Roman Numerical Converter” project of my own, the idea is to type the Arabic number into the input field and then it converts into a roman number. I’ve looked for a couple of guides on the internet, but the solution is not what I expect.
(I have my object with roman equivalents declared globally, it is like
const obj = {
…
X: 10,
V: 5,
IV: 4,
I: 1
}
)
My idea to implement is that the number value from the input goes to the loop, then the code searches for the biggest possible number from an object that can be fit inside the number from the input, for the next step the number found from the object is subtracted from the initial number from the input and then the product of the subtraction is used further unless it reaches 0 or the negative number and does it as many times as needed.
After that it should return the number values that were subtracted, get their keys from an object as strings and concatenate together into one string, so it will be possible to display the final roman number on the page.
That’s what I am struggling with, please help me
const numberInput = document.getElementById("number");
const convertBtn = document.getElementById("convert-btn");
const output = document.getElementById("output");
const removeHide = () => {
output.classList.remove("hide");
};
// removeHide();
// addOutput() handles the appearence of the #output
// the value always comes as a string
const addOutput = (num) => {
let roman = "";
const romanNumbers = {
M: 1000,
CM: 900,
D: 500,
CD: 400,
C: 100,
XC: 90,
L: 50,
XL: 40,
X: 10,
V: 5,
IV: 4,
I: 1
};
let a;
if (numberInput.value === "") {
removeHide();
return output.innerHTML = `<p>Please enter a valid number</p>`;
} else if (Number(numberInput.value) <= -1) {
removeHide();
return output.innerHTML = `<p>Please enter a number greater than or equal to 1</p>`;
} else if (Number(numberInput.value) >= 4000) {
removeHide();
return output.innerHTML = `<p>Please enter a number less than or equal to 3999</p>`;
} else {
for (let key in romanNumbers) {
a = Math.floor(num / romanNumbers[key]);
if (a >= 0) {
for (i = 0; i < a; i++) {
roman += key;
};
};
num = num % romanNumbers[key];
};
removeHide();
};
return roman, output.innerHTML = `<p>${roman}</p>`;
};
convertBtn.addEventListener('click', addOutput);
numberInput.addEventListener('keydown', (e) => {
if (e.key === "Enter") {
addOutput();
};
})
// Here is my latest piece of code that I have tried, I got random in here, since nothing worked out before