Roman Numeral Converter using object lookups

Tell us what’s happening:
Is using number as object key good practice?Preformatted text

Your code so far


function convertToRoman(num) {
let num_string = num.toString().split('').reverse().join('');
let roman_str = [];
for (let i = 0; i < num_string.length; i++) {
    let digit = parseInt(num_string[i]);
    let place =  Math.pow(10, i);
    roman_str.push(toRoman(digit, place));
}
return roman_str.reverse().join('');
}

function toRoman(digit, place) {
let roman = {
    0: "",
    1: "I",
    5: "V",
    10: "X",
    50: "L",
    100: "C",
    500: "D",
    1000: "M"
};
let roman_str = [];
switch (digit) {
    case 0:
    case 1:
    case 2:
    case 3: 
        roman_str.push(roman[place].repeat(digit));
        break;
    case 4:
        roman_str.push(roman[place]);
        roman_str.push(roman[5 * place]);
        break;
    case 5:
        roman_str.push(roman[5 * place]);
        break;
    case 6:
    case 7:
    case 8:
        roman_str.push(roman[5 * place]);
        roman_str.push(roman[place].repeat(digit - 5));
        break;
    case 9:
        roman_str.push(roman[place]);
        roman_str.push(roman[10 * place]);
        break;
}
return roman_str.join('');
}

console.log(convertToRoman(87));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36.

Challenge: Roman Numeral Converter

Link to the challenge:

I’m not sure if it is bad practice, but I wouldn’t do it because you can’t access the properties with dot notation anymore.

let test = roman.1 // throws reference error
1 Like

In the object.property syntax, the property must be a valid JavaScript identifier. (In the ECMAScript standard, the names of properties are technically “IdentifierNames”, not “Identifiers”, so reserved words can be used but are not recommended). For example, object.$1 is valid, while object.1 is not.

I think this would be of interest,


More here:

hello,
follow the bellow example i hope this will help you

function roman_to_Int(str1) {
if(str1 == null) return -1;
var no = char_to_int(str1.charAt(0));
var p, curr;

for(var i = 1; i < str1.length; i++){
curr = char_to_int(str1.charAt(i));
p = char_to_int(str1.charAt(i-1));
if(curr <= p){
no += curr;
} else {
no = no - p*2 + curr;
}
}

return no;
}

function char_to_int(c){
switch (c){
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
default: return -1;
}
}
console.log(roman_to_Int('XXVI'));
console.log(roman_to_Int('CI'));