Skip to content

Instantly share code, notes, and snippets.

@kakarukeys
Created May 21, 2017 13:49
Show Gist options
  • Save kakarukeys/31ec81968c8e629208eae630b88a3ce1 to your computer and use it in GitHub Desktop.
Save kakarukeys/31ec81968c8e629208eae630b88a3ce1 to your computer and use it in GitHub Desktop.
solution1 - string compression
// if performance is not important
function compress(str) {
/* shorten <str> by reducing consecutive character repetitions */
return str.replace(/(.)\1*/g, function(fullMatch, g1) {
return g1 + fullMatch.length;
});
}
console.assert(compress('') === '', "blank string");
console.assert(compress('a') === "a1", "single char");
console.assert(compress("aaaabbaaaababbbcccccccccccc") === "a4b2a4b1a1b3c12", "long string");
// if performance is important
function compress(str) {
/* shorten <str> by reducing consecutive character repetitions */
var count = 0,
lastChar = null,
c,
result = '';
if (!str) {
return '';
}
for (var i = 0, len = str.length; i < len; i++) {
c = str.charAt(i);
if (lastChar !== null && lastChar !== c) {
result += lastChar + count;
count = 1;
} else {
count++;
}
lastChar = c;
}
result += c + count;
return result;
}
console.assert(compress('') === '', "blank string");
console.assert(compress('a') === "a1", "single char");
console.assert(compress("aaaabbaaaababbbcccccccccccc") === "a4b2a4b1a1b3c12", "long string");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment