Code Wars: Mexican Wave Problem

Code Wars: Mexican Wave Problem

Task - In this simple Kata, your task is to create a function that turns a string into a 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.

Rules -

  1. The input string will always be the lower case but may be empty.

  2. If the character in the string is whitespace then pass over it as if it was an empty seat.

Example:

wave("hello") => ["Hello", "hEllo", "heLlo", "helLo", "hellO"]

Solution:

My approach to this problem is as follows:

  1. Create an empty array to push the words with uppercase letters and return this array in end.
  2. Use FOR loop to traverse the string passed in the function.
  3. Store each letter at each iteration in a variable.
  4. If the iteration is an empty string then pass.
  5. else use Slice and toUpperCase() method to edit the letter.
  6. Push each letter to the empty array created in step 1.
  7. return the array.
function wave(str){
  let waveArr = [];
  for(let i = 0; i < str.length; i++) {
    let letter = str[i];
    if (letter === " ") {
      continue;
    } else {
      waveArr.push(str.slice(0, i) + letter.toUpperCase() + str.slice(i + 1))
    } 
  }
  return waveArr;
}

Other Solutions:

  1. function wave(str){
     let result = [];
    
     str.split("").forEach((char, index) => {
         if (/[a-z]/.test(char)) {
             result.push(str.slice(0, index) + char.toUpperCase() + str.slice(index + 1));
         }
     });
    
     return result;
    }
    

2.

const wave = str => 
  [...str].map((s, i) => 
      str.slice(0, i) + s.toUpperCase() + str.slice(i + 1) 
  ).filter(x => x != str);
  1. If you like one-liners:
var wave=w=>[...w].map((a,i)=>w.slice(0,i)+a.toUpperCase()+w.slice(i+1)).filter(a=>a!=w)

Thank You for reading this. Tweet me if you have any questions!