This is helpfull,
but I don’t know why not to use a global variable !!
I’ve changed my code a little bit, and now it passed
still don’t under stand why not to use the global vairable ?
solution below :
const keys = {
"M":1000,
"CM":900,
"D":500,
"CD":400,
"C":100,
"XC":90,
"L":50,
"XL":40,
"X":10,
"IX":9,
"V":5,
"IV":4,
"I":1
}
// Removed the gloval variable, and provide it as function parameter with a default to empty string
function convertToRoman(num,tempRoman="") {
if (num <= 0) {
return tempRoman
}
for(const [i, val] of Object.entries(keys) ){
if(num >= val){
tempRoman = tempRoman + (i)
// recursively reduce the number, and provide the string at current state
return convertToRoman(num - val, tempRoman)
}
}
}
console.log(convertToRoman(29))
This is not a great challenge to use recursion on, in my opinion. It makes for convoluted logic. You can just replace the recursive call with a while loop.
WRT global variables…
Example:
var myGlobal = [1];
function returnGlobal(arg) {
myGlobal.push(arg);
return myGlobal;
} // unreliable - array gets longer each time the function is run
function returnLocal(arg) {
var myLocal = [1];
myLocal.push(arg);
return myLocal;
} // reliable - always returns an array of length 2
If a local variable is used rather than a global, each time the function is run it should be generating a new value. By using a global that never gets cleared between tests, the value is simply being combined with what is already in that global.
Ahaaaaa, I got it now
So basically, the test is getting the value from the previous state of the global variable
The test, does not re run and clear all values from the beginning,
I got it now
Soooo much appreciated boss