Skip to content

Instantly share code, notes, and snippets.

@victoriachuang
Created December 14, 2017 17:43
Show Gist options
  • Save victoriachuang/5506b3ce100e380ba52925f993cde5c1 to your computer and use it in GitHub Desktop.
Save victoriachuang/5506b3ce100e380ba52925f993cde5c1 to your computer and use it in GitHub Desktop.
Caesar Cipher
// Assumptions:
// All input characters that are uppercase should remain toUpperCase
// Non-alphabetical characters should remain the same
// Only check for non-uppercase vowels to capitalize
const vowels = ['a', 'e', 'i', 'o', 'u'];
// Helper function
const isVowel = char => vowels.includes(char);
const asciiShift = (input) => {
let shiftedString = '';
// iterate through input
const inputLength = input.length;
for (let i = 0; i < inputLength; i++) {
// only change alphabetical characters
if (input[i].match(/[a-zA-Z]/i)) {
// for each character, convert to ascii
const charToAscii = input.charCodeAt(i);
let newAsciiChar;
// if the character is uppercase
if ((charToAscii >= 65) && (charToAscii <= 90)) {
// characters at the end of the uppercase range should
// wrap to the beginning of the range
newAsciiChar = String.fromCharCode(((charToAscii - 65 + 1) % 26) + 65);
// the character is lowercase
} else if ((charToAscii >= 97) && (charToAscii <= 122)) {
newAsciiChar = String.fromCharCode(((charToAscii - 97 + 1) % 26) + 97);
}
// append new character to temp string
shiftedString += newAsciiChar;
} else {
// append non-alphabetical characters as-is
shiftedString += input[i];
}
}
let outputString = '';
// iterate through temp string
for (let k = 0; k < inputLength; k++) {
const currentChar = shiftedString[k];
// if the character is a vowel, capitalize it and append to output string
if (isVowel(currentChar)) {
outputString += shiftedString[k].toUpperCase();
// else append to string
} else {
outputString += shiftedString[k];
}
}
return(outputString);
}
const testString = 'Hello Annette!';
console.log(asciiShift(testString));
// Potential tests:
// Input and output are the same length
// Non-alphabetical characters remain at the same indices in input and output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment