Last active
August 29, 2015 14:06
-
-
Save jsatk/29e3c68ae8b2c9d65539 to your computer and use it in GitHub Desktop.
Counts the unique characters in a string
This file contains 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
var uniqueCharsInStringCounter = function (string) { | |
var countOfChars = {}, numberCountAndUniqueChars = '', chars, uniqueChars; | |
if (!string || typeof string !== 'string') { | |
throw new Error('Must call method with a string as an argument.'); | |
} | |
chars = string.split('').sort(); | |
uniqueChars = chars.filter(function (char, index, array) { | |
return array.indexOf(char) === index; | |
}); | |
for (var i = 0; i < chars.length; i++) { | |
countOfChars[chars[i]] = countOfChars[chars[i]] ? countOfChars[chars[i]] + 1 : 1; | |
} | |
for (var char in countOfChars) { | |
if (countOfChars.hasOwnProperty(char)) { | |
numberCountAndUniqueChars += countOfChars[char] + char; | |
} | |
} | |
return numberCountAndUniqueChars; | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment