Skip to content

Instantly share code, notes, and snippets.

@robotlolita
Created November 8, 2010 19:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robotlolita/668163 to your computer and use it in GitHub Desktop.
Save robotlolita/668163 to your computer and use it in GitHub Desktop.
function Counter(str) {
var filter_instance = this; // keep a reference to this object's instance
this.char_count = 0; // number of unique chars found
/* return a table mapping each char to it's number of occurrences */
function count_chars() {
var array = str.split("");
var table = {};
array.map(function(elm, index, a) {
/* this function is called in the context of `array`. Which means
* that we can't access `char_count` here using `this.char_count`,
* that would actually access `array.char_count`, which would
* return undefined!
*
* So, we use the reference we saved before instead.
*/
if (!table[elm]) { // new unique character
filter_instance.char_count++;
table[elm] = 1 }
else {
table[elm]++ }
});
return table;
}
this.count_chars = count_chars;
}
var my_counter = new Counter("some string of characters");
console.log(my_counter.count_chars());
console.log(my_counter.char_count);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment