Hi Damien,
Thinking through a problem and trying to figure out what needs to be done to solve it is the core of our job as programmer. So this is a good start (any start is better than none!)
Avoid using ‘var’. It is not wrong and you will find it in pre-ES6 code, but you should largely treat it as a thing of the past and declare variables with let/const.
Your code is doing 3 things:
- defines a roman object called ‘chart’
- implements a for loop with a random stop value of 1000 for index i (I mean I do not understand why you chose that)
- compares the input argument num with an return value for the index (if it exists, which is mostly not true)
So let’s have a closer look. Did you try a console log to see what your loop does return for your object value?
function convertToRoman(num) {
const chart = {
M: 1000,
CM: 900,
D: 500,
CD: 400,
C: 100,
XC: 90,
L: 50,
XL: 40,
X: 10,
}
for (let i = 1; i <= 10; i++) {
console.log(Object.values(chart)[i])
}
}
As you can see I reduced the index to be smaller or equal to 10 and my output is
900
500
400
100
90
50
40
10
undefined
undefined
That should give you already a clue on why this approach is not working. It loops through your object and simply returns the value for each index, and you have only 9 of them. Then you compare the returned value (for each of these values) with the number passed into the function. What is the chance someone asks for exactly 500 to be converted, rather than 2022? So this approach is not very robust.
So you need to restrict your look up to the length of your object, and you do need to gain access to the the key value (you could swap your key and value, so you can look up the number using the key and retrieve the value). In Rotimi’s answer here (Post your Roman Numeral Converter solutions here! (Fall 2022) - #5 by Timiphil) the loop is through all elements in the object and return the key (the variable is named i, but it is not really an index but rather the key).
Then also you need to think in how to process the problem. Solutions that are posted in this thread show different approaches. You could find the number of thousands, hundreds, etc and try to match your answer there. Or reduce the value with the largest amount (if possible) and balance it out with the matching character in the result.
Does this help in any way to develop an approach?