Home > OS >  TypeError: Cannot read property 'toUpperCase' of undefined |CodeWars|
TypeError: Cannot read property 'toUpperCase' of undefined |CodeWars|

Time:07-06

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..

CodePudding user response:

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.

CodePudding user response:

try this.

const arrChar = Array.from(str)[0] ?? '';

CodePudding user response:

The parameters given to the function could be an empty string which could in fact cause this property 'toUpperCase' undefined issue. Main reasons for this include:

  1. Calling the method on a class property that is not initialized to a string
  2. Calling the method on an array index that doesn't exist

So do a check on the arrChar value.

if(!Array.from(str)[0]){
    arrChar = "";
}

CodePudding user response:

ch is a any object , may be not a string , ch in ch.toUpperCase()

  • Related