Created
August 12, 2012 07:14
-
-
Save matthewmueller/3330386 to your computer and use it in GitHub Desktop.
Toggle between two or more functions
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
/** | |
* 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