Search code examples
javascriptnode.jsstringsubstringcoding-style

Recursive JS Function To Move Specific Characters To End Of String


For Example:

  1. moveAllXToEnd("xxre") --> "rexx"
  2. moveAllXToEnd("xxhixx") --> "hixxxx"
  3. moveAllXToEnd("xhixhix") --> "hihixxx"
function moveAllXToEnd(str, count = 1) {

    if (str.length <= 1) {
        return str;
    }

    // console.log(str.length, count);
    if (str.length === count) {
        return str;
    }

    if (str[count] === 'x') {
        // Removing the x and putting the '' empty string
        let splicedString = str.substr(0, count) + '' + str.substr(count + 1);
        // Adding back the 'x' to the end of the string
        splicedString += str[count];
        return moveAllXToEnd(splicedString, count + 1);
    }

    return moveAllXToEnd(str, count + 1);
}


Solution

  • Test whether the first character of the string argument is x. If so, return the recursive call concatenated with x - otherwise, return the first character concatenated with the recursive call:

    console.log(moveAllXToEnd("xxre")) // --> "rexx"
    console.log(moveAllXToEnd("xxhixx")) // --> "hixxxx"
    console.log(moveAllXToEnd("xhixhix")) // --> "hihixxx"
    function moveAllXToEnd(str) {
      if (str.length <= 1) {
        return str;
      }
      return str[0] === 'x'
        ? moveAllXToEnd(str.slice(1)) + 'x'
        : str[0] + moveAllXToEnd(str.slice(1));
    }

    The count variable doesn't look to serve a purpose.