Skip to content

Instantly share code, notes, and snippets.

@matthewmueller
Created August 12, 2012 07:14
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 matthewmueller/3330386 to your computer and use it in GitHub Desktop.
Save matthewmueller/3330386 to your computer and use it in GitHub Desktop.
Toggle between two or more functions
/**
* toggle between n functions
*
* Example:
*
* var a = function(p) { console.log("a:", p); };
* var b = function(p) { console.log("b:", p); };
*
* var func = toggle(a, b);
* func('hi') // => "a: hi"
* func('bonjour') // => "b: bonjour"
* func('hello') // => "a: hello"
*
*/
var toggle = exports.toggle = function() {
var self = this,
args = Array.prototype.slice.call(arguments),
len = args.length,
i = 0;
return function() {
var ret = args[i++].apply(self, arguments);
i = (i === len) ? 0 : i;
return ret;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment