So, here is the kata:
Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case).
Examples "the-stealth-warrior" gets converted to "theStealthWarrior" "The_Stealth_Warrior" gets converted to "TheStealthWarrior"
I came up with this solution (with a little help from Google):
function toCamelCase(str) {
const arrChar = Array.from(str)[0];
let result = '';
if (arrChar !== arrChar.toUpperCase()) {
result += str
.toLowerCase()
.replace(/[^a-zA-Z0-9]+(.)/g, (m, chr) => chr.toUpperCase());
} else if (arrChar === arrChar.toUpperCase()) {
result += (' ' + str)
.toLowerCase()
.replace(/[^a-zA-Z0-9]+(.)/g, (m, ch) => ch.toUpperCase());
}
return result;
}
It works perfect in Vs code, but CodeWars gives me this:
TypeError: Cannot read property 'toUpperCase' of undefined
at toCamelCase
at it
at begin
at it
at describe
at /runner/frameworks/javascript/cw-2.js:152:11
at Promise._execute
at Promise._resolveFromExecutor
at new Promise
at describe
at /home/codewarrior/index.js:23:5
at /home/codewarrior/index.js:33:5
at Object.handleError
Any ideas why? Thanks in advance..
In codewars the first test case that they provide is an empty string. Therefore array.from("")[0] will produce undefined and cause the error later on. This can be avoid by checking if the string is empty and returning it if it is. I would suggest to always look for edge cases that are described in the task definition and start your logic with them.