Home > OS >  JavaScript recursive function is returning strange value
JavaScript recursive function is returning strange value

Time:10-04

Here is my code, why it is returning 13 in place of 4:

const superNumber = (n) => {
  let nums = n.toString().split('').map(Number);
  let sum = parseInt(nums.reduce((x, y)=> x   y));
  console.log('Nums: ',nums, 'Sum: ', sum);
  if(sum > 9) {
     superNumber(sum);
  }
   return sum;
}

let result = superNumber(148);
console.log('Ans: ', result);

Here is the console log:

  • Nums: [1, 4, 8] Sum: 13
  • Nums: [1, 3] Sum: 4 // Calculated sum correctly but returning the previous value
  • Ans: 13

CodePudding user response:

You forgot a return there:

if (sum > 9) 
    return superNumber(sum);
//  ^^^^^^ here you forgot to return

const superNumber = (n) => {
  let nums = n.toString().split('').map(Number);
  let sum = parseInt(nums.reduce((x, y) => x   y));
  console.log('Nums:', nums.toString(), ' Sum:', sum);
  if (sum > 9) {
    return superNumber(sum);
  }
  return sum;
}

let result = superNumber(148);
console.log('Ans: ', result);

CodePudding user response:

if you don't want to mess up with the return...

const superNumber = n =>
  {
  let
    nums = Array.from(n.toString(10))
  , sum  = nums.reduce((s,v) => s    v, 0)
    ;
  console.log( 'Nums: ', ...nums, ' , Sum: ', sum );
 
  return  (sum < 10) ? sum :  superNumber(sum);
  }
 
console.log('Ans: ', superNumber(148));

  • Related