Code Wars: Mexican Wave
2 min readJul 26, 2021
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:
- Create an empty array to which we will push the words with uppercase letters and we will return this array in end.
- Use FOR loop to traverse the string passed in the function.
- Store each letter at each iteration in a variable.
- If the iteration is an empty string then pass.
- else use Slice and toUpperCase() method to edit the letter.
- Push each letter to the empty array created in step 1.
- 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!