Created
June 3, 2016 00:18
-
-
Save eternal44/9ae3cec03e57da3324647c34787e8aa1 to your computer and use it in GitHub Desktop.
Returns a map of characters & their consecutive frequency.
This file contains hidden or 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
// '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')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I also tried using a higher function to iterate with but I before the native for loop.