DEV Community

Discussion on: Easy peasy reverse words

Collapse
 
bhagatparwinder profile image
Parwinder 👨🏻‍💻

Julian, I believe Divyajyoti is missing a key part of the description (from my understanding). She wants to reverse the words in a string, not the whole string.

This is what your example produces:

const toReverse = 'hello bella cause birds fancy';
const reversed = toReverse.split('').reverse().join('');
console.log(reversed);
// "ycnaf sdrib esuac alleb olleh"

This is what her solution produces:

const revWords = (str, n) => {
  return str.split(' ').map(function (word) {
    return (word.length >= n) ? 
    word.split('').reverse().join('') : word;
  }).join(' ');
}

console.log(revWords("hello bella cause birds fancy", 5));
// olleh alleb esuac sdrib ycnaf

That being said, I feel the original solution could be improved. It could be simplified a lot. There is no need to know word length.

const reverseWordsInPlace = (input) => {
    return input.split(" ").map(
     word => word.split("").reverse().join("")
    ).join(" ");
}

console.log(reverseWordsInPlace("hello bella cause birds fancy car is a bmw"));
// "olleh alleb esuac sdrib ycnaf rac si a wmb"
// used an input with different word length to prove we shouldn't care about word length
Collapse
 
pujux profile image
Julian Pufler

Oh, yeah I totally missed that because I was on mobile. Thanks for clearing it up, your solution is probably the shortest you can do! 👍

Collapse
 
divyajyotiuk profile image
Divyajyoti Ukirde • Edited

If the question has word length specifically mentioned then you need to apply my solution. I have made the text bold, to avoid confusion. The n there is word-length basically and only those words need to be reversed that satisfy the word-length condition.

Thread Thread
 
bhagatparwinder profile image
Parwinder 👨🏻‍💻

Ah, you only want n length or above words in a string reversed in place. Now it makes more sense. Danke!