Home > Back-end >  what is the reason for the code not working as expected?
what is the reason for the code not working as expected?

Time:11-04

The project required is to make the uppercase letters to be lowercased and vice versa. I don't understand why my code isn't working as expected.

The code is below:

let start4 = 0;
let swappedName = "elZerO";

for (let i = 0; i < swappedName.length; i  ) {
  if (swappedName[i] === swappedName[i].toLowerCase()) {
    swappedName[i].toUpperCase();
  } else {
    swappedName[i].toLowerCase();
  }
  console.log(swappedName);
}

The result of the code was nothing changed in the text.

CodePudding user response:

It is not working because swappedName[i].toUpperCase(); and swappedName[i].toLowerCase(); are merely getting the upper and lowercase versions of the character at position i and discarding that result.

You need to update the string with the result.

Personally I would spread the string codepoints into an array [... swappedName], use array manipulation methods to change the codepoint at each position in the string, and then use Array#join to create the string to return.

Here's a solution using Array#map.

const invert = (s) => {
    const arr = [...s]
    return arr.map((cp) =>
        cp === cp.toLowerCase() 
            ? cp.toUpperCase() 
            : cp.toLowerCase()).join('')
}

let swappedName = "elZerO";
console.log(invert(swappedName))

CodePudding user response:

Break the problem into smaller steps.

  1. How can I swap the case for any given character?
  2. How can I map a sequence of characters to toggled characters?

Now, put the two together:

const toggleCharacterCase = (character) =>
  character === character.toLowerCase()
    ? character.toUpperCase()
    : character.toLowerCase();

const toggleCase = (str) => str
  .split('')
  .map(toggleCharacterCase)
  .join('');

const
  originalStr = 'elZerO',
  toggledStr = toggleCase(originalStr);

console.log(toggledStr); // ELzERo

  • Related