Skip to content

Instantly share code, notes, and snippets.

@jcoglan
Created August 26, 2008 14:02
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 jcoglan/7264 to your computer and use it in GitHub Desktop.
Save jcoglan/7264 to your computer and use it in GitHub Desktop.
// 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