Should I be creating an object like this?
let numChart = {
I: 1,
V: 5,
X: 10,
...}
Should I be creating an object like this?
let numChart = {
I: 1,
V: 5,
X: 10,
...}
I flipped the keys and values, but that’s how I did it.
Like this? Why do I have error I is not defined?
let numsChart = {
'1': I,
'5': V
}
Perhaps you didn’t change your other code to reflect flipping the keys and values. Hard to tell without seeing more code.
That is one way to do it another way is a switch statement. If you haven’t come across it yet:
You can express the same logic with a switch and a lookup object, but in this case I tend to find the lookup object leads to less repetition in the code.
I agree that it’s hard to say why your code isn’t working without seeing more. I’m not sure why you chose a string representation of a number as your key, but that could be your problem.
Because I need to convert incoming number parameter to a string to look at each index individually which I can’t do with a number data type. And no changing it to number property below has same error.
function convertToRoman(num) {
let x = num.toString();
let numsChart = {
1: I,
5: V
}
return num;
}
convertToRoman(36);
This doesn’t seem to be your whole code, this just returns the argument. To help further I think you need to post your complete code.
I also had this question but without seeing more code it is hard to say.
It was because no quotes around property values:
function convertToRoman(num) {
let x = num.toString();
let numsChart = {
1: 'I',
5: 'V',
10: 'X',
50: 'L',
100: 'C',
500: 'D',
1000: 'M'
}
if(numsChart.hasOwnProperty(num)) {
return numsChart[num];
}
return num;
}
convertToRoman(2);
Now I have no idea how to go about this. Is there like a isClosest method to see which property is closest to the parameter?
Think about making change. How do you write 8 in Roman numerals?
VII. I thought of an algorithm to go from roman numerals to a number, but the other way around seems very hard. I’m thinking loop through the object properties and if the property is greater than the num passed in then start with the one behind it?
You mean VIII, right?
I think you have the right idea, but I asked about making 8 to help refine the process.
Roman numerals are built from left to right. Why do we know that 8 starts with a V? Once we know it starts with a V, why do we know to add I and then another I and then one more I?
Bc the first object property greater than 8 is 10, so we start with the one before it which is 5: V
We try multiplying the 5: V by 2 and if the value exceeds 8 then by start adding the value before it 1: I?
Object property? I’m talking about pencil and paper.
If I’m doing this by hand, step by step, how do I do it?
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.