BorisWho
BorisWho

Reputation: 3

TypeError: Cannot read property 'toUpperCase' of undefined |CodeWars|

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

Upvotes: 0

Views: 2689

Answers (4)

nano71.com
nano71.com

Reputation: 88

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

Upvotes: 0

Martin Penkov
Martin Penkov

Reputation: 21

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 = "";
}

Upvotes: 1

MartinS
MartinS

Reputation: 126

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.

Upvotes: 1

user19483449
user19483449

Reputation:

try this.

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

Upvotes: 1

Related Questions