Skip to content

Instantly share code, notes, and snippets.

@mikepuerto
Last active October 14, 2015 11:46
Show Gist options
  • Save mikepuerto/bcc779e58dde4e3cc6c9 to your computer and use it in GitHub Desktop.
Save mikepuerto/bcc779e58dde4e3cc6c9 to your computer and use it in GitHub Desktop.
// 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