Skip to content

Instantly share code, notes, and snippets.

@eternal44
Created June 3, 2016 00:18
Show Gist options
  • Save eternal44/9ae3cec03e57da3324647c34787e8aa1 to your computer and use it in GitHub Desktop.
Save eternal44/9ae3cec03e57da3324647c34787e8aa1 to your computer and use it in GitHub Desktop.
Returns a map of characters & their consecutive frequency.
// 'AAAABBCDDDEEAA' => 'A4B2C1D3E2A2'
function countChars (str) {
var currentChar = str[0];
var charCount = 1;
var results = [];
for (var i = 1; i < str.length; i++) {
if(str[i] === currentChar) {
charCount++;
} else {
results.push(str[i - 1], charCount);
charCount = 1;
currentChar = str[i];
}
}
return results.join('');
}
console.log(countChars('AAAABBCDDDEEAA'))
@eternal44
Copy link
Author

eternal44 commented Jun 3, 2016

I also tried using a higher function to iterate with but I before the native for loop.

function countChars (str) {
  var currentChar = str[0];
  var charCount = 1;
  var results = [];

  Array.prototype.forEach.call(str, function(char, index) {
    if(index === 0) return

    if(str[index] === currentChar) {
      charCount++;
    } else {
      results.push(str[index - 1], charCount);
      charCount = 1;
      currentChar = str[index];
    }
  })
  return results.join('');
}
console.log(countChars('AAAABBCDDDEEAA'))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment