1

The prompt was:

Create a function that takes in a string and returns a "URL version" of the string. This simply involves replacing the spaces with %20.

It asked to solve the problem using recursion and using .replace is not allowed. Here is my solution but I understand the ouputArray is being mutated. Is there any other way to solve this without a mutation?

let inputString = "hello world I am fine";
let outputArray = [];

let stringToUrl = (inputString, n) => {
inputArray = [...inputString]
  if(n < inputArray.length) {
    if(inputArray[n] !== " ") {
        outputArray.push(inputArray[n])
      return stringToUrl(inputArray, n+1)
      } 
      else {
      outputArray.push("%20")
      return stringToUrl(inputArray, n+1)
      }
    } 
      return outputArray.join('');
  }
console.log(stringToUrl(inputString, 0))
0

4 Answers 4

2

Yes, you can do this with FP. In keeping with How do I ask and answer homework questions?, I won't reply with code, but with pointers.

If you weren't doing this with FP (but still had to write it yourself rather than using the string replace method, etc.), you'd probably use a loop building up a new string by looping through the original string character by character and either adding the original character to the new string or adding %20 to it.

In FP, loops are often done via recursion, and your instructions are to use recursion, so we'll do that instead.

Your function should handle the first character in the string it's given (either keeping it or replacing it with %20), and if that character is the only character, just return that updated "character;" otherwise, it should return the updated character followed by the result of passing the rest of the string (all but that first character) through your function again. That will work through the entire string via recursion, building up the new string. (No need for arrays, string concatenation and substring should be fine.)

Sign up to request clarification or add additional context in comments.

Comments

0

Here I have made some changes to your code. Hope this solves your problem. I don't have to use the second array but make changes to the original array.

let inputString = "hello world I am fine";
let stringToUrl = (inputString, n) => {
inputArray = [...inputString]
  if(n < inputArray.length) {
    if(inputArray[n] === " ") {
        inputArray[n] = "%20"
      return stringToUrl(inputArray, n+1)
    } 
    else {
      return stringToUrl(inputArray, n+1)
      }
    } 
      return inputArray.join('');
  }
console.log(stringToUrl(inputString, 0))

Comments

0
const replace = (char: string) => char === ' ' ? '%20' : char;

const convert = (str: string, cache = ''): string => {
    const [head, ...tail] = str;

    return head
        ? convert(
            tail.join(''),
            cache.concat(replace(head))
        )
        : cache
}

const result = convert("hello world I am fine") // hello%20world%20I%20am%20fine

Playground

I hope this task is not language agnostic, because JS is not best choise in terms of recursion optimization.

Comments

0

One option to do that could be using a call to stringToUrl and use an inner recursive function making use of default parameters passing the values of the variables as function arguments.

For example using an arrow function, and also passing a function as a parameter that does a check to either add %20 to the array with final characters:

const stringToUrl = str => {
    const func = (
        s,
        r = "",
        c = s.charAt(0),
        f = () => r += c === ' ' ? '%20' : c
    ) => s.length ? f() && func(s.substr(1), r) : r

    return func(str)
}

console.log(stringToUrl("hello world I am fine"));

Output

hello%20world%20I%20am%20fine

const stringToUrl = str => {
  const func = (
    s,
    r = "",
    c = s.charAt(0),
    f = () => r += c === ' ' ? '%20' : c
  ) => s.length ? f() && func(s.substr(1), r) : r

  return func(str)
}


[
  "",
  " ",
  "   ",
  "hello world I am fine"
].forEach(s =>
  console.log(`[${s}] --> ${stringToUrl(s)}`)
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.