Soy nuevo en javascript, estoy tratando de escribir una función que calcule el factorial de un número dado y también reemplace el cuarto elemento. Espero que cuando se ejecute el código anterior, debería producir 6GeXmanX pero en su lugar NaNXermXny
function Recursion(num) { if (num=== 0 || num===1){ return 1; } result= Recursion(num-1)*num; results = result + 'Germany' const str = results.split('') const nth = 4 var replaceWith = 'X' for (var i = nth-1; i < str.length-1; i+=nth){ str[i]= replaceWith; } //y = (results.join("")) return (str.join("")); } // code goes here // keep this function call here console.log(Recursion(3));Primero, necesitas dividir la función factorial en una función separada.
En segundo lugar, en la condición for , la i debería ser i < str.length no i < str.length - 1 ya que no iterará sobre la última letra.
function factorial(num) { if (num=== 0 || num===1){ return 1; } return factorial(num-1)*num; } function func(num) { let results = factorial(num) + 'Germany' const str = results.split('') const nth = 4 var replaceWith = 'X' for (var i = nth-1; i < str.length; i+=nth){ str[i]= replaceWith; } //y = (results.join("")) return (str.join("")); } // code goes here // keep this function call here console.log(func(3));Este es tu código:
function Recursion(num) { //When this condition don't comply, the return of Recursion is str.join("") //You can add a console.log to see for yourself //So you need to split the functions if (num === 0 || num === 1) { return 1; } result = Recursion(num - 1) * num; console.log("recursive") results = result + 'Germany' const str = results.split('') const nth = 4 var replaceWith = 'X' //It should be only str.length for (var i = nth - 1; i < str.length - 1; i += nth) { str[i] = replaceWith; } return (str.join("")); } console.log(Recursion(5))Entonces necesitas hacer estas modificaciones:
function Factorial(num){ return num < 2 ? num : num * Factorial(num-1) } function Replace(num){ const newString = (Factorial(num)+"Germany").split('') const replaceWith = 'X' let replaceEvery = 4 for (var i = replaceEvery - 1; i < newString.length; i += replaceEvery) { newString[i] = replaceWith; } return (newString.join("")); } console.log(Replace(6));