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.
“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)
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.
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.
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.
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.