使用模 ( %) 运算符和三元运算符 ( ?) 计算正确的加密/解密密钥。
使用扩展运算符 ( ...) 和Array.prototype.map()遍历给定字符串的字母。
使用String.prototype.charCodeAt() 和 String.fromCharCode()适当地转换每个字母,忽略特殊字符、空格等。
使用Array.prototype.join()将所有字母组合成一个字符串。
传递true给最后一个参数 ,decrypt以解密加密字符串。
JavaScript
const caesarCipher = (str, shift, decrypt = false) => {
const s = decrypt ? (26 - shift) % 26 : shift;
const n = s > 0 ? s : 26 + (s % 26);
return [...str]
.map((l, i) => {
const c = str.charCodeAt(i);
if (c >= 65 && c <= 90)
return String.fromCharCode(((c - 65 + n) % 26) + 65);
if (c >= 97 && c <= 122)
return String.fromCharCode(((c - 97 + n) % 26) + 97);
return l;
})
.join('');
};
示例
caesarCipher('Hello World!',-3);// 'Ebiil Tloia!'
caesarCipher('Ebiil Tloia!',23,true);// 'Hello World!'
更多内容请访问我的网站:https://www.icoderoad.com