Skip to content

Instantly share code, notes, and snippets.

@TheEyesightDim
Last active December 17, 2018 19:01
Show Gist options
  • Save TheEyesightDim/6db11141614303740b4902298787bf54 to your computer and use it in GitHub Desktop.
Save TheEyesightDim/6db11141614303740b4902298787bf54 to your computer and use it in GitHub Desktop.
Rotate alphabet characters in a string by an arbitrary amount
//needed to make friendly for map function, which expects function taking dereferenced string index as argument
function charCodeOfChar(character){
return character.charCodeAt(0);
}
//String's prototype function will give weird UTF-16 literal output otherwise
function charFromCharCode(charCode){
return String.fromCharCode(charCode);
}
//shifter for individual characters
function rotXShifter(asciiCode, shift) {
shift = shift > 0? shift : (shift%26) + 26;
if (asciiCode > 64 && asciiCode < 91)
return ((asciiCode - 65 + shift) % 26) + 65;
if (asciiCode > 96 && asciiCode < 123)
return ((asciiCode - 97 + shift) % 26) + 97;
return asciiCode
}
//shifter for complete strings, ignores non-ASCII alphabetical characters
function stringShifter(string, displacement = 13){
return string.split('')
.map(charCodeOfChar)
.map( x => rotXShifter(x, displacement) )
.map(charFromCharCode)
.join('');
}
console.log(stringShifter('Victory!'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment