Caesar cipher

    0

    0

    Giovanny Gongora

    Codiga's TypeScript Recipes

    Encrypts or decrypts a given string using the Caesar cipher.

    const caesarCipher = (str: string, shift: number, decrypt: boolean = false) => {
      const s: number = decrypt ? (26 - shift) % 26 : shift;
      const n: number = 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('');
    };
    
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    Legal
    • Security
    • Privacy Policy
    • Code Privacy
    • Terms of Service
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.