Reversing the prime length words - JavaScript


We are required to write a JavaScript function that takes in a string that contains strings joined by whitespaces. Our function should create a new string that has all the words from the original string and the words whose length is a prime number reversed i.e. words with length 2, 3, 5, 7, 100, etc.

Example

Following is the code −

const str = 'His father is an engineer by profession';
// helper functions
const isPrime = n => {
   if (n===1){
      return false;
   }else if(n === 2){
      return true;
   }else{
      for(let x = 2; x < n; x++){
         if(n % x === 0){
            return false;
         }
      }
      return true;
   };
};
const reverseString = str => str.split('').reverse().join('');
const reversePrime = str => {
   return str.split(' ').reduce((acc, val) => {
      const { length } = val;
      if(isPrime(length)){
         acc += reverseString(val)+' ';
      }else{
         acc += val+' ';
      };
      return acc;
   }, '');
};
console.log(reversePrime(str));

Output

Following is the output in the console −

siH father si na engineer yb profession

Updated on: 18-Sep-2020

148 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements