Skip to content

Instantly share code, notes, and snippets.

@danielpowell4
Created October 21, 2016 06:04
Show Gist options
  • Save danielpowell4/2950f1786436701deb29f4045896968c to your computer and use it in GitHub Desktop.
Save danielpowell4/2950f1786436701deb29f4045896968c to your computer and use it in GitHub Desktop.
Shifts letters to next letter in alphabet (c -> d, z -> a) and ensures vowels in new string are CAPS in Javascript ES6. Includes tests!
/* -- Problem --
* Have the function alphabetShift(str) take the str parameter
* being passed and modify it using the following algorithm.
* Replace every letter in the string with the letter following it
* in the alphabet (ie. c becomes d, z becomes a). Then capitalize
* every vowel in this new string (a, e, i, o, u) and finally return
* this modified string.
*/
/* -- Examples --
*
* Input:"hello*3"
* Output:"Ifmmp*3"
*
* Input:"fun times!"
* Output:"gvO Ujnft!"
*
*/
const alphabetShift = (str) => {
let ary = str.split('');
const length = ary.length;
let new_ary = [];
for (let i = 0; i < length; i++ ) {
if( /^[a-yA-Y]+$/.test(ary[i]) ) {
let next_letter = String.fromCharCode( (ary[i]).charCodeAt(0) + 1 );
new_ary.push( "eiou".includes(next_letter) ? next_letter.toUpperCase() : next_letter );
} else if ( /^[zZ]+$/.test(ary[i]) ){
new_ary.push('A');
} else {
new_ary.push(ary[i]);
}
}
return new_ary.join('');
}
// -- Test "suite"
// tallies
let pass = 0;
let fail = 0;
// basic test function for newString
const test = (name, str, expected) => {
console.log(' testing ' + name);
let newString = alphabetShift(str);
if (newString === expected ){
pass++;
console.log(' - pass! 🐳\n');
} else {
fail++;
console.log(' - fail! 🐞 got ' + newString + ' expected ' + expected + '\n');
}
};
// test runner
console.log('\nStarting Test Suite for alphabetShift.js \n');
test('next letter', 'jklm', 'klmn');
test('next letter from caps', 'JKLM', 'KLMN');
test('z and Z to A', 'zZ', 'AA');
test('vowels to caps', 'zdhnt', 'AEIOU');
test('special chars', '/ ! @ # $ % ^ & * ; : " " ( ) [ ] { } /', '/ ! @ # $ % ^ & * ; : " " ( ) [ ] { } /');
console.log('\nResults are in:');
console.log(' ' + pass + ' Wins, ' + fail + ' Loses'); // print tallies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment