Skip to content

Instantly share code, notes, and snippets.

@kaimallea
Last active December 21, 2015 04:08
Show Gist options
  • Select an option

  • Save kaimallea/6246849 to your computer and use it in GitHub Desktop.

Select an option

Save kaimallea/6246849 to your computer and use it in GitHub Desktop.
function encode(str) {
if (!str) { return; }
if (/[^a-z]/i.test(str)) { throw Error('Letters only'); }
var len = str.length,
i = 1,
output = '',
counter = 1;
for (; i <= len; i++) {
// Am I a repeat character?
if (str[i] === str[i-1]) {
// Yes
counter++;
} else {
// No
output += counter + str[i-1];
counter = 1;
}
}
return output;
}
console.log( encode('aaabbbccczz') );
// => 3a3b3c2z
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment