The task is to implement a function that converts snake case to camel case.
The boilerplate code
function snakeToCamel(str) {
// your code here
}
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;
Loop through the string manually
while (i < str.length)
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] !== '_'
)
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;
Skip the underscore and the next character
i += 2;
Copy as-is if there is no underscore
else {
result += str[i];
i++;
}
Return the final string
return result;
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;
}
That's all folks!
Top comments (0)