-1

My function is supposed to separate a camel-cased string (e.g. "camelCase" into "camel Case"). My logic is basically that I split the string into an array, identify uppercase characters, and then splice in a space character before the uppercase character. Returning a joined array. I could figure out a different solution but, I more curious about why my function isn't returning anything.

My function:

function solution(str) {
  let splitStr = str.split("");
  for(let i=0; i<splitStr.length; i++){
   if(splitStr[i]===splitStr[i].toUpperCase()){
     splitStr.splice(i, 0, " ");
   }
  }
  return splitStr.join("");
}

I would understand if this threw an error but, it doesn't return anything. Not "undefined" or "null", just nothing. So I'm not so much looking for a solution to this challenge as I am curious about why this function spits out nothing. Any help is appreciated!

TOOTCODER
  • 25
  • 1
  • 1
  • 2
  • maybe you would want to check your console and try to get an error message at least to help know what's wrong. your function seems okay. try commenting out the for loop and see if it returns anything – emmaakachukwu May 13 '21 at 21:27
  • Try using regex instead.. [check this out](https://stackoverflow.com/questions/7225407/convert-camelcasetext-to-sentence-case-text#answer-7225450) – emmaakachukwu May 13 '21 at 21:35
  • Making an infinite loop since `" " === " ".toUpperCase()` is true. Not a good idea to use `splice()` inside a for loop. Better to work backwards if you do so as not to conflict with indexing – charlietfl May 13 '21 at 21:36

2 Answers2

0

First of all, I recommend using regex.

Since you asked for an explanation for your problem, you have created an infinity loop when the whitespace is inserted and compared in the subsequent loop. The engine gets caught in the infinity loop; hence there is no output. As a rule of thumb, you should avoid looping over a mutable construct and modifying it.

Here's a working solution on the basis of your code:

function solution(str) {
  const splitStr = str.split("");
  let result = [];
  for(let i=0; i<splitStr.length; i++){
   if(splitStr[i] === splitStr[i].toUpperCase()){
     result.splice(i, 0, ` ${splitStr[i]}`);
     continue;
   }
   result.push(splitStr[i]);
  }
  return result.join("");
}
alexanderdavide
  • 1,487
  • 3
  • 14
  • 22
0

Here's a solution, your code was entering an infinite loop, so of course you'd get no return.

function solution(str) {
    let splitStr = str.split("");
    for (let i = 0; i < splitStr.length - 1; i++) {
        if (splitStr[i] === splitStr[i].toUpperCase()) {
            splitStr.splice(i, 0, " ");
            i++;
        }
    }
    return splitStr.join("");
}

console.log(solution('raRaRambolaRombala'));

Regex would be a "better" way to do this, but you'd have a bit more overhead.

storjak
  • 58
  • 6