mexicanWave.js

Codewars 알고리즘 풀이


Problem

  • In this simple Kata your task is to create a function that turns a string into a Mexican Wave.
    • 문자열을 Mexican Wave로 바꾸는 함수를 작성한다.
  • You will be passed a string and you must return that string in an array where an uppercase letter is a person standing up.
    • 대문자가 하나씩 일어서는 배열 내 문자열을 반환한다.
  • The input string will always be lowercase but maybe empty.
    • 입력(input) 문자열은 항상 소문자이거나 비어 있을 수 있다.
  • If the character in the string is whitespace then pass over it as if it was an empty seat.
    • 문자열의 문자가 공백(whitespace)이면 빈 자리로 넘긴다.



Solution 01

function mexicanWave(str) {
  let result = [];
  
  for (let i = 0; i < str.length; i++) {
    let arr = str.split('');
    
    if (arr[i] !== ' ') {
      arr[i] = arr[i].toUpperCase();
      result.push(arr.join(''));
    }
  }
  return result;
}

mexicanWave('hello');     // ['Hello', 'hEllo', 'heLlo', 'helLo', 'hellO']
mexicanWave('codewars');  // ['Codewars', 'cOdewars', 'coDewars', 'codEwars', 'codeWars', 'codewArs', 'codewaRs', 'codewarS']


Solution 02

function mexicanWave(str) {
  let result = [];
  
  for (let i = 0; i < str.length; i++) {
    result.push(str.substring(0, i) + str.charAt(i).toUpperCase() + str.slice(i + 1));
  }
  return result.filter(i => i !== str);
}

mexicanWave('hello');     // ['Hello', 'hEllo', 'heLlo', 'helLo', 'hellO']
mexicanWave('codewars');  // ['Codewars', 'cOdewars', 'coDewars', 'codEwars', 'codeWars', 'codewArs', 'codewaRs', 'codewarS']


Solution 03

function mexicanWave(str) {
  return [...str].map((i, index) => str.slice(0, index) + i.toUpperCase() + str.slice(index + 1)).filter(i => i !== str);
}

mexicanWave('hello');     // ['Hello', 'hEllo', 'heLlo', 'helLo', 'hellO']
mexicanWave('codewars');  // ['Codewars', 'cOdewars', 'coDewars', 'codEwars', 'codeWars', 'codewArs', 'codewaRs', 'codewarS']