For some reason my solution for the Roman Numeral Converter is not accepted. Solution seems to be working fine in chrome snippets. Any help would be greatly appreciated. Code is as follows.
let result = [];
const romanNumeralsMapping = [
{
1000: "M",
900: "CM",
500: "D",
400: "CD",
100: "C",
90: "XC",
50: "L",
40: "XL",
10: "X",
9: "IX",
5: "V",
4: "IV",
1: "I",
},
];
//extract all keys in an array so we can find key value less than or equal to given argument
let keys = Object.keys(romanNumeralsMapping[0]);
function convertToRoman(num) {
//find key value less than or equal to num argument, if not met then return 1000 as it is the largest
let closestValue = keys.reduce(function (acc, currElem, index) {
return Math.abs(currElem <= num) && Math.abs(keys[index + 1] > num) ? currElem : acc;}, 1000);
//push the closest value to result array
result.push(romanNumeralsMapping[0][closestValue]);
//find the remaining difference
let remainingValue = num - closestValue;
//use recursion to find all values until difference is 0
if (remainingValue === 0) {
return result.join("");
} else {
return convertToRoman(remainingValue);
}
}
convertToRoman(109);
Technically, all you have to do is reset the array after the function for it to work with the tests.
// result array
// your function
result = [];
// or
// result.length = 0;
Don’t get in a habit of doing this though.
You can change the function signature to have two parameters, the number and the result array function convertToRoman(num, result = []) {} and then pass result to the nested function call return convertToRoman(remainingValue, result)
I agree that globals are usually a bad idea, especially functions with implicit global side effects. But it is possible for a function to have global side effects and not be an issue. It is more common with DOM manipulation to see functions with global side effects and even then it isn’t always the best idea.
Tried putting global variable inside the main function and created another function to push values to the global variable but this again did not work with test. Thank you very much for the solution above. I have now resolved this issue with the argument array passed in as a second parameter. I am not familiar with test. During test looks like values are stacked if a global function is used with recursion as the function seemed to work when tested individually.