Skip to content

Instantly share code, notes, and snippets.

@alexdong
Created May 25, 2014 23:28
Show Gist options
  • Save alexdong/403feb16a651b0243775 to your computer and use it in GitHub Desktop.
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.
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