Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Reversing the prime length words - JavaScript
We are required to write a JavaScript function that takes in a string that contains words joined by whitespaces. Our function should create a new string that has all the words from the original string, but words whose length is a prime number should be reversed (i.e., words with length 2, 3, 5, 7, 11, etc.).
What are Prime Numbers?
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. For example: 2, 3, 5, 7, 11, 13, etc.
Algorithm
Our approach involves three main steps:
- Create a helper function to check if a number is prime
- Create a helper function to reverse a string
- Split the input string into words, check each word's length, and reverse if prime
Example
Following is the complete code:
const str = 'His father is an engineer by profession';
// Helper function to check if a number is prime
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;
}
};
// Helper function to reverse a string
const reverseString = str => str.split('').reverse().join('');
// Main function to reverse words with prime length
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
siH father si na engineer yb profession
How It Works
Let's trace through the example string 'His father is an engineer by profession':
- 'His' (length 3) - 3 is prime ? reversed to 'siH'
- 'father' (length 6) - 6 is not prime ? stays 'father'
- 'is' (length 2) - 2 is prime ? reversed to 'si'
- 'an' (length 2) - 2 is prime ? reversed to 'na'
- 'engineer' (length 8) - 8 is not prime ? stays 'engineer'
- 'by' (length 2) - 2 is prime ? reversed to 'yb'
- 'profession' (length 10) - 10 is not prime ? stays 'profession'
Optimized Version
Here's a more concise version using array methods:
const reversePrimeWords = str => {
const isPrime = n => n > 1 && ![...Array(n).keys()].slice(2).some(i => n % i === 0);
return str.split(' ')
.map(word => isPrime(word.length) ? word.split('').reverse().join('') : word)
.join(' ');
};
const testStr = 'His father is an engineer by profession';
console.log(reversePrimeWords(testStr));
siH father si na engineer yb profession
Conclusion
This solution efficiently identifies words with prime-length characters and reverses them while keeping other words intact. The key is combining prime number detection with string manipulation techniques.
