Skip to content

Instantly share code, notes, and snippets.

@petercr
Created April 24, 2022 21:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petercr/dbb3fa59cc6f908effe7e7aa05508224 to your computer and use it in GitHub Desktop.
Save petercr/dbb3fa59cc6f908effe7e7aa05508224 to your computer and use it in GitHub Desktop.
My Solution to Caesar's Cipher in TypeScript: I had to set to JS to get syntax highlighting
function caesarCipher(phraze: string, offBy: number): string {
function hasLowerCase(str: string): boolean {
return /[a-z]/.test(str);
}
function hasUpperCase(str: string): boolean {
return /[A-Z]/.test(str);
}
// Here's that alphabet string
const aToZ = "abcdefghijklmnopqrstuvwxyz";
const uppercaseAtoZ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// Loop over the offBy value if it's greater than 26
// until it's less than 26
while (offBy > 26) {
offBy -= 26;
}
// Loop over that string
const encryptedString = phraze.split("").map((current, i) => {
// Hold lowercase boolean
let isLowerCase: boolean;
// If it's not a letter just return the char
if (hasLowerCase(current.toString())) {
isLowerCase = true;
} else if (hasUpperCase(current.toString())) {
isLowerCase = false;
} else {
return current;
}
// Get index from the alphabet
let locationIndex = aToZ.indexOf(current.toLowerCase());
// logic to make sure it's under 26 and a letter
if (isLowerCase && locationIndex + offBy <= 25) {
return aToZ[locationIndex + offBy];
} else if (!isLowerCase && locationIndex + offBy <= 25) {
const cryptoLetterIndex = locationIndex + offBy;
return uppercaseAtoZ[cryptoLetterIndex];
} else if (isLowerCase && locationIndex + offBy > 25) {
return aToZ[locationIndex + offBy - 25];
} else if (locationIndex + offBy > 25 && !isLowerCase) {
return aToZ[locationIndex + offBy - 25].toLocaleUpperCase();
} else {
return current;
}
});
return encryptedString.join("");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment