
使用模 (?%) 運(yùn)算符和三元運(yùn)算符 (??) 計(jì)算正確的加密/解密密鑰。
使用擴(kuò)展運(yùn)算符 (?...) 和Array.prototype.map()遍歷給定字符串的字母。
使用String.prototype.charCodeAt() 和 String.fromCharCode()適當(dāng)?shù)剞D(zhuǎn)換每個(gè)字母,忽略特殊字符、空格等。
使用Array.prototype.join()將所有字母組合成一個(gè)字符串。
傳遞true給最后一個(gè)參數(shù) ,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!'
更多內(nèi)容請(qǐng)?jiān)L問(wèn)我的網(wǎng)站:https://www.icoderoad.com