Codewars: Stop gninnipS My sdroW!
1 min readFeb 10, 2021
Problem: 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.
Examples:
spinWords( “Hey fellow warriors” ) => returns “Hey wollef sroirraw” spinWords( “This is a test”) => returns “This is a test”
- Basic Solution:
function spinWords(str){
let string = str;
let final = [];
let strList = str.split(' ');
for(var i = 0; i<strList.length; i++) {
if(strList[i].length>4 ){
final.push(strList[i].split('').reverse().join(''));
} else{
final.push(strList[i]);
}
}return final.join(' ');
}
2. Using .map() and Ternary operator:
function spinWords(words){
return words.split(' ').map(w => w.length < 5 ? w : w.split('').reverse().join('')).join(' ');
}
3. Using Ternary operator:
function spinWords(str){
return str.split(' ').map(spinSingleWord).join(' ');
}
function spinSingleWord(word){
return word.length>4 ? word.split('').reverse().join('') : word;
}
4. Using Regex:
function spinWords(string){
return string.replace(/\w{5,}/g, function(w) { return w.split('').reverse().join('') })
}
Thank you so much for reading!