Roman Numeral Converter looks like it passes tests but doesn't

Roman Numeral Converter looks like it passes tests but doesn't
0

#1

Tell us what’s happening:
To me it looks like my code passes the tests. When I run the tests my code only passes the test for convertToRoman(2). What am I missing? Thank you.

Your code so far


// convert standard numbers 1 - 3999 to roman numerals

let baseRomNum = {
  1 : "I", 2: "II", 3: "III", 4: "IV",  5 : "V", 6: "VI", 7: "VII", 8: "VIII", 9: "IX",
  10 : "X", 20: "XX", 30: "XXX", 40: "XL", 50 : "L", 60: "LX", 70: "LXX", 80: "LXXX", 90: "XC",
  100 : "C", 200: "CC", 300: "CCC", 400: "CD", 500 : "D", 600: "DC", 700: "DCC", 800: "DCCC", 900: "CM",
  1000 : "M", 2000: "MM", 3000: "MMM", 4000: "MMMM"
}

let romNum = "";

function convertToRoman(num) {
    for (var remains = num; remains > 0; remains = remains - Object.keys(baseRomNum)[Object.keys(baseRomNum).findIndex(function(currVal){ return currVal > remains })-1] ){
  romNum = romNum + baseRomNum[Object.keys(baseRomNum)[Object.keys(baseRomNum).findIndex(function(currVal){ return currVal > remains })-1]]
    }
 return JSON.stringify(romNum);
}

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/roman-numeral-converter/


#2

Try removing JSON.stringify(romNum) and leave romNum only. You don’t need to stringify a string


#3

@saclark12000, I also would suggest you to try to solve it with functional programming. It really looks hard-coded. Try same with this initial variable:

const baseRomNum = {
  1: 'IXCM',
  5: 'VLD'
};

Good luck!


#4

Thanks for taking a look. I originally did not have the JSON.stringify(romNum) returned but since it wasn’t passing the tests, I put it there so it would look exactly like what is being asked for as output. Even without stringing the string it fails all tests, except convertToRoman(2).


#5

It passes the first test only because you declaring romNum outside your function and so it doesn’t reset on each invoke. Put it inside the function.


#6

Ah ok, that makes sense and it now passes all the tests. Thanks again for your help!