Code Wars: Mexican Wave

Nilesh Saini
2 min readJul 26, 2021

--

Photo by Silas Baisch on Unsplash

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 lower case but maybe 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 which we will push the words with uppercase letters and we will 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);

3. 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!

--

--

Nilesh Saini
Nilesh Saini

Written by Nilesh Saini

Web Developer/ Front-end engineer who loves solving Rubik's Cube

No responses yet