Fancy DSA Fancy DSA
数据结构
算法
LeetCode
  • 关于
  • 导航 (opens new window)
  • 分类
  • 标签
  • 归档
设计模式 (opens new window)
博客 (opens new window)
GitHub (opens new window)

Jonsam NG

想的更多,也要想的更远
数据结构
算法
LeetCode
  • 关于
  • 导航 (opens new window)
  • 分类
  • 标签
  • 归档
设计模式 (opens new window)
博客 (opens new window)
GitHub (opens new window)
  • 开始上手
  • Plan 计划
  • Roadmap 路线
  • 算法简介
  • Sort 排序

  • Search 搜索

  • Recursive 递归

  • Graph 图

  • Tree 树

  • Math 数学

  • Hash 哈希

  • String 字符串

  • BitManipulation 位操纵

  • Backtracking 回溯

  • DynamicProgramming 动态规划

  • Cache 缓存

  • Array 数组

  • Ciphers 密码学

    • Atbash
    • CaesarsCipher
      • 实现
    • KeyFinder
    • KeywordShiftedAlphabet
    • ROT13
    • VigenereCipher
    • XORCipher
  • Conversions 转换

  • ProjectEuler 欧拉计划

  • 其他

  • 算法
  • Ciphers 密码学
jonsam
2022-09-26
目录

CaesarsCipher

# 实现

# JavaScript

/**
 * @function caesarsCipher
 * @description - In cryptography, a Caesar cipher, also known as Caesar's cipher, the shift cipher, Caesar's code or Caesar shift, is one of the simplest and most widely known encryption techniques. It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example, with a left shift of 3, D would be replaced by A, E would become B, and so on. The method is named after Julius Caesar, who used it in his private correspondence.
 * @see - [wiki](https://en.wikipedia.org/wiki/Caesar_cipher)
 * @param  {string} str - string to be encrypted
 * @param {number} rotation - the number of rotation, expect real number ( > 0)
 * @return {string} - decrypted string
 */
const caesarsCipher = (str, rotation) => {
  if (typeof str !== 'string' || !Number.isInteger(rotation) || rotation < 0) {
    throw new TypeError('Arguments are invalid')
  }

  const alphabets = new Array(26)
    .fill()
    .map((_, index) => String.fromCharCode(97 + index)) // generate all lower alphabets array a-z

  const cipherMap = alphabets.reduce(
    (map, char, index) => map.set(char, alphabets[(rotation + index) % 26]),
    new Map()
  )

  return str.replace(/[a-z]/gi, (char) => {
    if (/[A-Z]/.test(char)) {
      return cipherMap.get(char.toLowerCase()).toUpperCase()
    }

    return cipherMap.get(char)
  })
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
编辑 (opens new window)
上次更新: 2022/10/28, 17:30:16
Atbash
KeyFinder

← Atbash KeyFinder→

最近更新
01
0-20题解
10-31
02
本章导读
10-31
03
算法与转换:Part1
10-28
更多文章>
Theme by Vdoing | Copyright © 2022-2022 Fancy DSA | Made by Jonsam by ❤
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式