Created
August 26, 2008 14:02
-
-
Save jcoglan/7264 to your computer and use it in GitHub Desktop.
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
// Converts any function to accept continuation-passing style | |
// | |
// var add = function(a, b) { | |
// return a + b; | |
// }; | |
// | |
// var addcps = add.toCPS(); | |
// | |
// addcps(3, 4, function(x) { alert(x) }); | |
Function.prototype.toCPS = function() { | |
var direct = this; | |
return function() { | |
var args = [], i = arguments.length, | |
cps, context, result; | |
while (i--) args[i] = arguments[i]; // (1) | |
context = (args[args.length-2] instanceof Function) | |
? args.pop() : null; // (2) | |
cps = args.pop(); | |
result = direct.apply(this, args); // (3) | |
cps.call(context, result); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment