The challenge: Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed (Just like the name of this Kata). Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present.
Example:
spinWords( "Hey fellow warriors" )
=> returns "Hey wollef sroirraw"
At the moment I have this
function spinWords(str) { var splitArray = str.split(' ') for (var i = 0; i < splitArray.length; i++) { if (splitArray[i].length > 5) { var long = splitArray[i].split('').reverse('').join('') return long i++ } else { var short = splitArray[i] return short i++ } } }
As I said in the title, this is working properly but will only return the first element in the array as reversed or not. Can anyone smarter than me please explain why the loop is not looping? Thank you for your time.
Advertisement
Answer
you are almost there..
- using for loop, you do not want to do another i++..
- you said that it would be 5 or more.. so it should be >=5
- return terminates the for loop, so use it last..
the modified function can look like this:
function spinWords(str){ var splitArray = str.split(' '); var spinnedWords = ''; for (var i = 0; i < splitArray.length; i++) { if (splitArray[i].length >= 5) { var long = splitArray[i].split('').reverse('').join(''); spinnedWords = spinnedWords.concat(' ' + long); } else { var short = splitArray[i] spinnedWords = spinnedWords.concat(' ' + short); } } return spinnedWords.trim(); }