Last active
October 14, 2015 11:46
-
-
Save mikepuerto/bcc779e58dde4e3cc6c9 to your computer and use it in GitHub Desktop.
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
// example input 'aaaabbcccdaa' | |
// example output 'a4b2c3da2' | |
function compress(str) { | |
var input = str.split('') | |
, count = 1 | |
, ret = []; | |
for (var i = 0, len = input.length; i < len; i++) { | |
if (input[i] === input[i + 1]) count++; | |
else { | |
ret.push(count > 1 ? (input[i] + count) : input[i]) | |
count = 1 | |
} | |
} | |
return ret.join(''); | |
} | |
console.log(compress('aaaabbcccdaa')); // >> 'a4b2c3da2' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment