Skip to content

Instantly share code, notes, and snippets.

@jsatk
Last active August 29, 2015 14:06
Show Gist options
  • Save jsatk/29e3c68ae8b2c9d65539 to your computer and use it in GitHub Desktop.
Save jsatk/29e3c68ae8b2c9d65539 to your computer and use it in GitHub Desktop.
Counts the unique characters in a string
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