toWeirdCase.js

Codewars 알고리즘 풀이


Problem

  • Write a function that accepts a string, and returns the same string with all even indexed characters in each word upper cased, and all odd indexed characters in each word lower cased.
    • 짝수 인덱스는 대문자로, 홀수 인덱스는 소문자로 변환한다.
  • The passed in string will only consist of alphabetical characters and spaces.
    • 문자열은 알파벳 문자와 공백(spaces)으로만 구성된다.



Solution 01

function toWeirdCase(str) {
  let index = 0;
  let result = '';
  
  for (let i = 0; i < str.length; i++) {
    if (str[i] === ' ') {
      result += ' ';
      index = 0;
    } else if (index % 2 === 0) {
      result += str[i].toUpperCase();
      index++;
    } else if (index % 2 !== 0) {
      result += str[i].toLowerCase();
      index++;
    }
  }
  return result;
}

toWeirdCase('');                // ''
toWeirdCase('codewars');        // CoDeWaRs
toWeirdCase('Codewars');        // CoDeWaRs
toWeirdCase('coDEwaRS');        // CoDeWaRs
toWeirdCase('code wars');       // CoDe WaRs
toWeirdCase('This is a test');  // ThIs Is A TeSt


Solution 02

function toWeirdCase(str) {
  let index = 0;
  let result = '';
  
  for (let i = 0; i < str.length; i++) {
    result += index % 2 === 0 ? str[i].toUpperCase() : str[i].toLowerCase();
    
    str[i] === ' ' ? (index = 0) : index++;
  }
  return result;
}

toWeirdCase('');                // ''
toWeirdCase('codewars');        // CoDeWaRs
toWeirdCase('Codewars');        // CoDeWaRs
toWeirdCase('coDEwaRS');        // CoDeWaRs
toWeirdCase('code wars');       // CoDe WaRs
toWeirdCase('This is a test');  // ThIs Is A TeSt


Solution 03

function toWeirdCase(str) {
  return str.split(' ').map(word => {
    return word.split('').map((letter, index) => {
      return index % 2 === 0 ? letter.toUpperCase() : letter.toLowerCase();
    }).join('');
  }).join(' ');
}

toWeirdCase('');                // ''
toWeirdCase('codewars');        // CoDeWaRs
toWeirdCase('Codewars');        // CoDeWaRs
toWeirdCase('coDEwaRS');        // CoDeWaRs
toWeirdCase('code wars');       // CoDe WaRs
toWeirdCase('This is a test');  // ThIs Is A TeSt


Solution 04

function toWeirdCase(str) {
  return str.replace(/(\w{1,2})/g, i => i[0].toUpperCase() + i.slice(1));
}

toWeirdCase('');                // ''
toWeirdCase('codewars');        // CoDeWaRs
toWeirdCase('Codewars');        // CoDeWaRs
toWeirdCase('coDEwaRS');        // CoDeWaRs
toWeirdCase('code wars');       // CoDe WaRs
toWeirdCase('This is a test');  // ThIs Is A TeSt