Hey all, a little stuck on the Roman Numeral Converter project and would really appreciate some help. Somehow, each time the converter pushes an answer to the array it instead creates a new array. Because of this, the numerals are showing up in output in the wrong order. I can’t figure out how to fix this. Is there a way to fix it, or should I try a different approach to the converter project?
Link to the project: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures-v8/build-a-roman-numeral-converter-project/build-a-roman-numeral-converter
JavaScript I wrote so far:
const input = document.getElementById("number"); //1
const convertBtn = document.getElementById("convert-btn"); //2
const output = document.getElementById("output"); //3
input.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
checkInput();
}
}); //if press enter (instead of button)
convertBtn.addEventListener("click", () => {
checkInput();
}); //if click button
function checkInput() {
output.innerText = "";
if (input.value === "") {
output.innerText = "Please enter a valid number"; //4
} else if (input.value <= -1) {
output.innerText = "Please enter a number greater than or equal to 1"; //5
} else if (input.value >= 4000) {
output.innerText = "Please enter a number less than or equal to 3999"; //6
} else {
count(input.value);
}
}; // This all works
const count = (input) => {
console.log(input)
const answer = [];
if (input >= 1000) {
count(input - 1000);
answer.push("M");
} else if (input >= 900) {
count(input - 900);
answer.push("CM");
} else if (input >= 500) {
count(input - 500);
answer.push("D");
} else if (input >= 400) {
count(input - 400);
answer.push("CD");
} else if (input >= 100) {
count(input - 100);
answer.push("C");
} else if (input >= 90) {
count(input - 90);
answer.push("XC");
} else if (input >= 50) {
count(input - 50);
answer.push("L");
} else if (input >= 40) {
count(input - 40);
answer.push("XL");
} else if (input >= 10) {
count(input - 10);
answer.push("X");
} else if (input >= 9) {
count(input - 9);
answer.push("IX");
} else if (input >= 5) {
count(input - 5);
answer.push("V");
} else if (input >= 4) {
count(input - 4);
answer.push("IV");
} else if (input >= 1) {
count(input - 1);
answer.push("I");
} else {
return "0";
}
output.innerText += answer;
console.log(answer)
};
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Roman Numeral Converter</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<input id="number" type="number"></input>
<button id="convert-btn">Convert</button>
<div id="output"></div>
<script src="script.js"></script>
</body>
</html>