|
| 1 | +function caesarCipher(str, k) { |
| 2 | + // Helper function to shift a single character by k positions |
| 3 | + function shiftChar(char, k) { |
| 4 | + const isUpperCase = /[A-Z]/.test(char); |
| 5 | + const alphabetSize = 26; |
| 6 | + |
| 7 | + const baseCharCode = isUpperCase ? 'A'.charCodeAt(0) : 'a'.charCodeAt(0); |
| 8 | + const shiftedCharCode = ((char.charCodeAt(0) - baseCharCode + k) % alphabetSize + alphabetSize) % alphabetSize + baseCharCode; |
| 9 | + |
| 10 | + return String.fromCharCode(shiftedCharCode); |
| 11 | + } |
| 12 | + |
| 13 | + let result = ''; |
| 14 | + |
| 15 | + for (let i = 0; i < str.length; i++) { |
| 16 | + const char = str[i]; |
| 17 | + |
| 18 | + if (/[A-Za-z]/.test(char)) { |
| 19 | + result += shiftChar(char, k); |
| 20 | + } else { |
| 21 | + result += char; // Non-alphabetic characters remain unchanged |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + return result; |
| 26 | +} |
| 27 | + |
| 28 | +// Examples |
| 29 | +console.log(caesarCipher("middle-Outz", 2)); // ➞ "okffng-Qwvb" |
| 30 | +console.log(caesarCipher("Always-Look-on-the-Bright-Side-of-Life", 5)); // ➞ "Fqbfdx-Qttp-ts-ymj-Gwnlmy-Xnij-tk-Qnkj" |
| 31 | +console.log(caesarCipher("A friend in need is a friend indeed", 20)); // ➞ "U zlcyhx ch hyyx cm u zlcyhx chxyyx" |
0 commit comments