ภาพรวม
บทความนี้สาธิตวิธีเลื่อนตัวอักษรทุกตัวในสตริงไปข้างหน้า 1 ตำแหน่งในอัลฟาเบท (A→B, Z→A) ซึ่งเป็น Caesar Cipher ด้วย Shift = 1
ตัวอย่าง
Input: 'how are you'
Output: 'ipx bsf zpv'
การนำไปใช้
const isAlpha = (code) =>
(code >= 65 && code <= 90) || (code >= 97 && code <= 122);
const isLast = (code) => code === 90 || code === 122; // Z or z
const nextLetterString = (str) => {
return [...str].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('how are you')); // ipx bsf zpv
ผลลัพธ์
ipx bsf zpv
การขยาย: Caesar Cipher ทั่วไป (Shift ใดๆ ก็ได้)
const caesarCipher = (str, shift = 1) => {
shift = ((shift % 26) + 26) % 26; // Normalize shift
return [...str].map(char => {
const code = char.charCodeAt(0);
if (code >= 65 && code <= 90) { // A-Z
return String.fromCharCode((code - 65 + shift) % 26 + 65);
}
if (code >= 97 && code <= 122) { // a-z
return String.fromCharCode((code - 97 + shift) % 26 + 97);
}
return char; // Non-alphabetic
}).join('');
};
console.log(caesarCipher('Hello World!', 3)); // Khoor Zruog!
console.log(caesarCipher('Khoor Zruog!', -3)); // Hello World! (ถอดรหัส)
ROT13 (กรณีพิเศษ Shift = 13)
const rot13 = (str) => caesarCipher(str, 13);
// ROT13 มีคุณสมบัติ: เข้ารหัสและถอดรหัสด้วยฟังก์ชันเดียวกัน
การจัดการ Unicode (Thai, Emoji, อื่นๆ)
const shiftUnicode = (str, shift = 1) =>
[...str].map(c => String.fromCodePoint(c.codePointAt(0) + shift)).join('');
// หมายเหตุ: สำหรับ Thai/Unicode จะเลื่อน Code Point ตรงๆ ไม่ใช่เฉพาะอักษร
การประยุกต์ใช้
- Basic Encryption / Obfuscation
- Puzzle Games
- Text Encoding/Decoding Exercises
- ROT13 สำหรับการซ่อน Spoiler ใน Forum
ข้อควรระวัง
- ทำงานได้เฉพาะ A-Z, a-z (ASCII Letters)
- ไม่รองรับ Accented Characters (é, ñ, ü ฯล฿)
- สำหรับ Unicode จริง ควรใช้ Library เช่น
caesar-shiftหรือเขียนเองด้วย Unicode Ranges