Tell us what’s happening:
The tests pass for anything like “9”, “10”, “20”, but not the four specific number tests like 1023, etc. Please help me understand what has gone wrong.
Initially I thought it the issue lied in concatenating the array into a string, but if that was the problem shouldn’t it not work for the test of the number 9?
Your code so far
<!-- file: index.html -->
/* file: script.js */
/* ---------------
DECLARING MY VARIABLES
--------------- */
const userInput = document.getElementById("number");
const convertBtn = document.getElementById("convert-btn");
const restartBtn = document.getElementById("restart-btn");
const outputMsg = document.getElementById("output");
const output = document.getElementById("output-box");
const romanToNum = {
'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
};
let roman = [];
/* ---------------
CHECKING USER INPUT
--------------- */
// first I need to check if the user input is legitimate numbers
const checkInput = () => {
convertBtn.classList.add("hidden");
let userInt = parseInt(userInput.value, 10);
if (userInt === "" || !userInt) {
output.classList.toggle('hidden')
outputMsg.innerHTML =
'<p>Please enter a valid number</p>'
// "Please enter a number greater than or equal to 1"
// "Please enter a number less than or equal to 3999"
} else if (userInt < 1 || userInt > 3999) {
output.classList.toggle('hidden')
if (userInt < 1) {
outputMsg.innerHTML =
'<p>Please enter a number greater than or equal to 1</p>'
} else if (userInt > 3999) {
outputMsg.innerHTML =
'<p>Please enter a number less than or equal to 3999</p>'
}
} else {
output.classList.toggle('hidden')
const convert = (x) => {
for (let key in romanToNum) {
let remainder = x - romanToNum[key];
if (romanToNum[key] > x) {
continue
} else if (remainder === 0) {
roman.push(key);
let romanStr = roman.join('');
outputMsg.innerHTML = `<p id="output"> ${romanStr} </p>`;
return romanStr;
} else if (remainder > 0) {
roman.push(key);
convert(remainder);
let romanStr = roman.join('');
outputMsg.innerHTML = `<p id="output"> ${romanStr} </p>`;
return romanStr;
}
}
};
convert(userInt);
};
}
convertBtn.addEventListener("click", checkInput);
restartBtn.addEventListener("click", restart);
function restart() {
userInput.value = "";
roman = [];
output.classList.toggle("hidden");
convertBtn.classList.remove("hidden");
}
/* file: styles.css */
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36
Challenge Information:
Build a Roman Numeral Converter Project - Build a Roman Numeral Converter