Recursive string reversal function in javascript?

前端 未结 12 1493
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 08:48

I\'m a pretty experienced frontend engineer with a weak CS background. I\'m trying to get my head around the concept of recursion. Most of the examples and purported explana

相关标签:
12条回答
  • 2020-12-03 09:19

    According to the MDN Web Docs, you should use substring() instead of substr():

    Warning: Although String.prototype.substr(…) is not strictly deprecated (as in "removed from the Web standards"), it is considered a legacy function and should be avoided when possible. It is not part of the core JavaScript language and may be removed in the future. If at all possible, use the substring() method instead.

    Additionally, if no index is provided as a parameter to charAt(), the default is 0.

    Therefore, we can write a recursive one-liner to reverse a string using a ternary operator and by applying the logic described above:

    const reverse_string = s => s === '' ? '' : reverse_string(s.substring(1)) + s.charAt();
    
    console.log(reverse_string('Hello, world!')); // !dlrow ,olleH

    0 讨论(0)
  • 2020-12-03 09:19

    The base case that I am using for exiting the recursion is when the the length decrease to 0

    On each recursive call we will take out the last character of the string and append it with the result that we will get from recursive call of a string, which is smaller in size as the last character is removed using slice.

    function reverse(str){
     if(str.length===0)
        return "";
    
    return str[str.length-1]+reverse(str.slice(0,str.length-1));
    }
    
    0 讨论(0)
  • 2020-12-03 09:25

    A tail recursive version, just for kicks (even though JavaScript doesn't perform tail call elimination):

    function reverse(str) {
      function r(s, acc) {
        return (s.length == 0) ? acc : r(s.substr(1), s.charAt(0) + acc);
      };
      return r(str, '');
    };
    
    0 讨论(0)
  • 2020-12-03 09:25

    //call this function with the string as parameter

    function strrev(str) {
        return str.length !== 1 ? strrev(str.slice(1))+str[0] : str;
    }
    
    0 讨论(0)
  • 2020-12-03 09:26

    Something like:

    function reverse (str) {
        if (str === "") {
            return "";
        } else {
            return reverse(str.substr(1)) + str.charAt(0);
        }
    }
    

    So the function is recursive as it calls itself to do the work.

    0 讨论(0)
  • 2020-12-03 09:30

    It is verbose, but I like making it easy to understand in logical steps:

    function rev(soFar, count){
       console.log("asString: " + soFar );
       console.log("count: " + count);
       var len = soFar.length;
       var ret = soFar;//ret needs to be a reference to soFar
       if(len > count){
          var subd = soFar.substring(1,len);
          var first = soFar[0];
          //we want to inject the first letter at the index position one back from the length, minus what the count is at this point
          var indexOfInsert = len-1 - count;//so if count is 0 and length is 5, we want 4 (4 -0)
          var asArray = subd.split("");
          asArray.splice(indexOfInsert,0,first);
          count++;//need to increment count for the next round
          var asString = "";
        //recreate as string, not array - the default toString() makes this a comma delimited string. It is best toi just recreate it in a loop
        for(var i = 0; i<len; i++){
            asString+=asArray[i];
        }
        ret = rev(asString,count);//ret always needs to be reassigned
    }
    //only get here when count is greater than the length of the original string
    return ret;//will always be a reference to soFar, which is being reassigned in the recursive loop
    

    }

    Then call it like:

    var reversed = rev("Hello",0);
    console.log("result",reversed);
    
    0 讨论(0)
提交回复
热议问题