DEV Community

Discussion on: Help with Code

Collapse
 
deadlybyte profile image
Carl Saunders • Edited

The above code contains multiple issues, that'll try to explain and how they can be fixed.

Original

function crazyCaps (string1) {
  const lower_string = string1.toLowerCase();
  let crazystring = ''; 
  for (let i=0; i<lower_string.length; i++) {
    const Crazy = lower_string[i];
    if (i%2 ===1) crazystring +=Crazy[i].toUpperCase();
    else crazyString +=Crazy[i];
  }
  return crazystring; 
}

Running the above function crazyCaps('Adamsmith') within the console produced the first error:

Uncaught ReferenceError: crazyString is not defined

This is due to the fact you've interchanged the variable name crazystring with crazyString, these need to reference the same variable name. As you've declared the crazystring variable then I would suggest that the crazyString is changed to crazystring.

Refactor 1

function crazyCaps (string1) {
  const lower_string = string1.toLowerCase();
  let crazystring = ''; 
  for (let i=0; i<lower_string.length; i++) {
    const Crazy = lower_string[i];
    if (i%2 ===1) crazystring +=Crazy[i].toUpperCase();
    else crazystring +=Crazy[i];
  }
  return crazystring;
}

Running the above function crazyCaps('Adamsmith') within the console produced the second error:

Uncaught TypeError: Cannot read property 'toUpperCase' of undefined

This is due to the fact the Crazy variable is being accessed with an indexer Crazy[i], but it's not an array, it's a string. So we need to change all references to Crazy[i] to just Crazy.

Working Version - Refactor 2

function crazyCaps (string1) {
  const lower_string = string1.toLowerCase();
  let crazystring = ''; 
  for (let i=0; i<lower_string.length; i++) {
    const Crazy = lower_string[i];
    if (i%2 ===1) crazystring +=Crazy.toUpperCase();
    else crazystring +=Crazy;
  }
  return crazystring;
}

Ultimately the above issues / errors could've been avoid if a static typing language was used such as TypeScript or Flow. Also think about adding unit tests via Jest or another testing framework.

TypeScript Version - Refactor 3

const crazyCaps = (stringToConvert?: string): string => {
  if (stringToConvert) {
    const stringToLowerCase: string = stringToConvert.toLowerCase();
    let crazyString: string = ''; 
    for (let index: number = 0; index < stringToLowerCase.length; index++) {
      const crazyCharacter: string = stringToLowerCase[index];
      if (index % 2 === 1) {
        crazyString += crazyCharacter.toUpperCase();
      } else {
        crazyString += crazyCharacter;
      }
    }

    return crazyString;
  }
  return null;
}

TypeScript Playground Version

Hope this makes sense and let me know if you need any further help with the explanation.