Viết hàm nhận câu, đảo ngược các từ có độ dài là số nguyên tố (2, 3, 5, 7, 11...).
Ví dụ
Chuỗi: 'His father is an engineer by profession'
- His (3) → siH
- father (6) → giữ
- is (2) → si
- an (2) → na
- engineer (8) → giữ
- by (2) → yb
- profession (10) → giữ
Giải pháp
Mã triển khai:
const str = 'His father is an engineer by profession';
const isPrime = n => {
if (n <= 1) return false;
if (n === 2) return true;
if (n % 2 === 0) return false;
for (let x = 3; x * x <= n; x += 2) {
if (n % x === 0) return false;
}
return true;
};
const reversePrime = str =>
str.split(' ').map(w => isPrime(w.length) ? [...w].reverse().join('') : w).join(' ');
console.log(reversePrime(str));
Kết quả
Đầu ra trong console:
siH father si na engineer yb profession