Created
May 25, 2014 23:28
-
-
Save alexdong/403feb16a651b0243775 to your computer and use it in GitHub Desktop.
This implements a stateful function in javascript using closure. The same construct requires either a singleton class or a static variable in other languages.
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
var pick_color = (function(str) { | |
// We use a circular buffer here to allocate the colors. `label_color_map` | |
// is a hash with key as `str` and value is the index into the `colors` | |
// list. The following 'static' variables keep the state within the function. | |
var label_color_map = {}, | |
current_color_idx = 0, | |
colors = ['#a6cee3', '#1f78b4', '#b2df8a', '#33a02c', '#fb9a99', | |
'#e31a1c', '#fdbf6f', '#ff7f00', '#cab2d6', '#6a3d9a', '#ffff99', '#b15928']; | |
return function(str) { | |
if (!_.has(label_color_map, str)) { | |
current_color_idx = (current_color_idx + 1) % colors.length; | |
label_color_map[str] = current_color_idx; | |
} | |
return colors[label_color_map[str]]; | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment