Created
December 7, 2013 02:57
-
-
Save hauntedhost/7836744 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| // Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore ('_'). | |
| // Examples: | |
| // solution('abc') // should return ['ab', 'c_'] | |
| // solution('abcdef') // should return ['ab', 'cd', 'ef'] | |
| function paddedPairs(str) { | |
| var pairs = ['']; | |
| for (var i = 0; i < str.length; i++) { | |
| var lastPos = pairs.length - 1, | |
| letter = str[i]; | |
| if (pairs[lastPos].length < 2) { | |
| pairs[lastPos] += letter; | |
| } else { | |
| if (i == str.length - 1) letter += '_'; | |
| pairs.push(letter); | |
| } | |
| } | |
| return pairs; | |
| } | |
| // --------------------- | |
| Array.prototype.lastPlus = function (n) { | |
| return this[this.length - 1] += n; | |
| } | |
| Array.prototype.lastLength = function (n) { | |
| return (this[this.length - 1].length === n); | |
| } | |
| function paddedPairs(str){ | |
| var pairs = ['']; | |
| for (var i = 0; i < str.length; i++) { | |
| var letter = str[i]; | |
| (pairs.lastLength(2)) ? pairs.push(letter) : pairs.lastPlus(letter); | |
| } | |
| if (pairs.lastLength(1)) pairs.lastPlus('_'); | |
| return pairs; | |
| } | |
| // --------------------- | |
| function paddedPairs(str) { | |
| return (str + '_').match(/.{2}/g); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment