Last active
December 24, 2015 16:19
-
-
Save CarlinCanales/6827331 to your computer and use it in GitHub Desktop.
This is a little challenge another developer hit me with. It will return the first letter after the first set of repeated letters in a string. For example, in aardvark it will return the 'r' after 'aa'. It will also return the letter in the correct case.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function aardvark(str){ | |
var len = str.length, tempStr, iteration; | |
// if str is 2 characters or less return null right away | |
if(len < 3) return null; | |
// temporarily convert str to all lowercase to properly compare each character | |
tempStr = str.toLowerCase(); | |
// if string length is even iterate length - 2, else length - 1 | |
if(len % 2 === 0){ | |
iteration = len - 2; | |
}else{ | |
iteration = len - 1; | |
} | |
// iterate over tempStr to compare all characters equally | |
for (var i = 0; i < iteration; i++) { | |
// if two adjacent characters match return the following character from the original string to preserve case | |
if(tempStr[i] === tempStr[i+1]){ | |
// if str is only 3 characters and the last 2 match (ex. 'add') this will attempt to | |
// return the 4th character which doesn't exist. instead of returning undefined we want | |
// to catch this and explicitly return null | |
if(!str[i+2]) return null; | |
// return character from original string to preserve case | |
return str[i+2]; | |
} | |
} | |
// if we've made it this far there were no repeating characters, or the only repeating characters were at the end of the string | |
return null; | |
} | |
//console.log(aardvark("aardvark")); | |
//console.log(aardvark("little")); | |
//console.log(aardvark("craddles")); | |
//console.log(aardvark("LiTtLe")); | |
//console.log(aardvark("Carlin")); | |
//console.log(aardvark("Barrero")); | |
//console.log(aardvark("BarrEro")); | |
//console.log(aardvark("tall")); | |
//console.log(aardvark("no 'x' 120044()[]\"{}<>\/$~^|-+%*=!?#&@_:;.,''innixon")) | |
//console.log(aardvark("bb")); | |
//console.log(aardvark("bba")); | |
//console.log(aardvark("abc")); | |
//console.log(aardvark("add")); | |
//console.log(aardvark("llat")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment