DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 109

The task is to implement a function that converts snake case to camel case.

The boilerplate code

function snakeToCamel(str) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

To convert from snake_case to camelCase, it is required that the connecting underscore be removed and the next word has its first letter capitalised. Leading underscores, trailing underscores and double underscores should be kept.

Initialize variables to build the final string and a pointer to walk through the string

let result = '';
let i = 0;
Enter fullscreen mode Exit fullscreen mode

Loop through the string manually

while (i < str.length)
Enter fullscreen mode Exit fullscreen mode

Determine the conditions that ensure only underscores that connect words are removed

if (
  str[i] === '_' &&
  i > 0 &&
  i < str.length - 1 &&
  /[a-zA-Z]/.test(str[i + 1]) &&
  str[i - 1] !== '_'
)
Enter fullscreen mode Exit fullscreen mode

Convert the next character correctly. If it is lowercase, convert to uppercase. If it is uppercase, leave it

const nextChar = str[i + 1];

result += nextChar >= 'a' && nextChar <= 'z'
  ? nextChar.toUpperCase()
  : nextChar;
Enter fullscreen mode Exit fullscreen mode

Skip the underscore and the next character

i += 2;
Enter fullscreen mode Exit fullscreen mode

Copy as-is if there is no underscore

else {
  result += str[i];
  i++;
}
Enter fullscreen mode Exit fullscreen mode

Return the final string

return result;
Enter fullscreen mode Exit fullscreen mode

The final code

function snakeToCamel(str) {
  // your code here
 let result = "";
 let i = 0;

 while(i < str.length) {
  if(str[i] === '_' && i > 0 && i < str.length - 1 &&  /[a-zA-Z]/.test(str[i + 1]) && str[i - 1] !== '_') {
   const nextChar = str[i + 1];
   result += nextChar >= 'a' && nextChar <= 'z' ? nextChar.toUpperCase() : nextChar;
   i += 2;
  } else {
    result += str[i];
    i++;
  }
 }
 return result;
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)