Created
November 8, 2010 19:49
-
-
Save robotlolita/668163 to your computer and use it in GitHub Desktop.
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
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