am guru prasath
am guru prasath

Reputation: 293

Javascript | Recursive function I created returns undefined along with the proper answer

When I run the below recursive function it returns "CLundefined" here "CL" is the proper answer. I have defined all the variables as far as I know. What is the problems.

var roman = {
  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
};


function convertToRoman(num) {
  for (var key in roman) {
    var check = num >= roman[key];
    console.log(key);
    if (check) {
        return key + convertToRoman( num -= roman[key])
  }
}
}

convertToRoman(150);

Upvotes: 0

Views: 61

Answers (3)

Rafael
Rafael

Reputation: 7746

Just for giggles, but anyone looking for an iterative example:

const ROMAN = {
    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
};

let x = Object.keys(ROMAN).reverse();
let y = Object.values(ROMAN).reverse();

function toRoman(n) {
    n = (n|=0) < 0 ? -n : n;
    if (n === 0) return null;
    
    let s = "";
    while (n !== 0) {
        let i = ((n >= y[y.length-1] && y.length) ||
                 y.findIndex(m => m>n)) - 1;
        
        s += x[i];
        n -= y[i];
    }
    return s;
}

console.log([
    0, -11, 100, 103, 234, 1928, 9832, 221, -23.3, 10.1, -0.3
].map(toRoman));

Upvotes: 0

Ele
Ele

Reputation: 33736

You're missing the recursion termination condition, in this case, num === 0. This is to stop the recursion loop.

var roman = {  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};
function convertToRoman(num) {
  if (num === 0) return "";
  
  for (var key in roman) {
    if (num >= roman[key]) return key + convertToRoman(num -= roman[key]);
  }
}

console.log(convertToRoman(150));

Upvotes: 2

Randy Casburn
Randy Casburn

Reputation: 14185

Eventually check is false so the if() block does not run. Therefore, the default return is provided as the function return - that default is, you guessed it, undefined.

Would be best to use a local variable in your function (outside the for loop) and then return the variable.

Upvotes: 1

Related Questions