Convert a Function to Continuation-Passing Style

Here's a snippet that converts a normal Javascript function to its Continuation-Passing style equivalent:

function asCPS(f){
  var _f = function(){
    var callback = arguments[arguments.length - 1];
    var args = Array
      .prototype.slice
      .call(arguments, 0, arguments.length - 1)
    var retVal = f.apply(this, args)
    if (callback) callback(retVal)
  }
  _f.name = f.name
  return _f
}

So you have a normal function, say add():

function add(one, other){
  return one + other;
}

Convert it:

add = asCPS(add)

Now you can call it and get the result inside a callback, like so:

add(1, 2, function(sum){
  console.log('sum: ' + sum)
})
blog comments powered by Disqus