ฟังก์ชันนี้เปลี่ยนตัวอักษรทุกตัวในสตริงเป็นตัวถัดไปในอักษรอังกฤษ (a→b, z→a, A→B, Z→A) สัญลักษณ์อื่นคงเดิม
ตัวอย่าง
// Input: 'how are you' // Output: 'ipx bsf zpv'
ตัวอย่างโค้ด
const str = 'how are you';
const isAlpha = code => (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
const isLast = code => code === 90 || code === 122;
const nextLetterString = str => {
return str.split('').reduce((acc, val) => {
const code = val.charCodeAt(0);
if (!isAlpha(code)) {
return acc + val; // ไม่ใช่ตัวอักษร คงเดิม
}
if (isLast(code)) {
return acc + String.fromCharCode(code - 25); // z→a, Z→A
}
return acc + String.fromCharCode(code + 1); // ตัวถัดไป
}, '');
};
console.log(nextLetterString(str));
การทำงาน
charCodeAt(0)- ได้รหัส ASCII- ตรวจสอบช่วง A-Z (65-90) และ a-z (97-122)
- z (122) → a (97) = -25, Z (90) → A (65) = -25
- ตัวอักษรอื่น → +1
ผลลัพธ์
ipx bsf zpv
ประยุกต์ใช้: Caesar cipher (shift=1) การเข้ารหัสง่ายๆ การสร้างปริศนา