Ever been to a football match, your team is playing for all their worth and the crowd is enchanted. Then some drunk guys on the other side of the stadium start shouting “WAVE! WAVE”. All of a sudden the a Mexican wave starts from their end, ripples all the way to where you are and you can’t help but join in?
Well, that’s today’s problem. Given a string that is all lower caps, return an array in which each element is the same string but each letter is capitalized in a simulation of a Mexican wave.
Example
“hello world” outputs
[
'Hello world',
'hEllo world',
'heLlo world',
'helLo world',
'hellO world',
'hello World',
'hello wOrld',
'hello woRld',
'hello worLd',
'hello worlD'
]
Code language: JSON / JSON with Comments (json)
First Wave
I’ll admit I overthought this one at first. My first approach was to create a new array with the number of elements equal to the number of letters in the input string. Then I filled that array with the string and mapped through each element, converted the element to an array, spliced the target letter using the index, and then joined it back to a string.
This had a problem that spaces would come out as undefined elements. so I tacked on a filter at the end.
function wave(str) {
const array = new Array(str.length).fill(str).map((word, index) => {
if (word[index] !== ' ') {
const arr = word.split("")
arr.splice(index, 1, word[index].toUpperCase())
return arr.join("")
}
})
return array.filter(word => word !== undefined)
}
Code language: JavaScript (javascript)
Take 2
Ok, this wasn’t the best, I thought. Maybe I could refactor and make it better? So I looked at everything I was doing and improved it a little so that I didn’t need to create then fill by switching to Array.prototype.from.
function wave(str) {
const array = <strong><em>Array</em></strong>.from({length: str.length}, (_, index) => {
if (str[index] !== ' ') {
return str.slice(0, index) + str[index].toUpperCase() + str.slice(index + 1)
}
})
return array.filter(word => word)
}
Code language: JavaScript (javascript)
Facepalm
After taking a break and getting some coffee and a doughnut and when I sat down again and looked at the problem I had a facepalm moment. I was overthinking this. I didn’t need to create the array upfront nor did I need the tacked-on filter.
One of the problems I’ve observed in myself is that the more I use JavaScript Array functions like map, filter, and reduce the more I forget the traditional tools. Like a simple for loop. So another 2 minute refactor later I had a simpler approach which I was much happier with.
function wave(str) {
const array = []
for (let index = 0; index < str.length; index++) {
if (str[index] !== ' ') {
array.push(str.slice(0, index) + str[index].toUpperCase() + str.slice(index + 1))
}
}
return array
}
Code language: JavaScript (javascript)
I love football and this was a fun little challenge. If you have any comments or suggestions let me know over on Twitter @phoexer and as always happy coding.