Created
July 18, 2010 15:42
-
-
Save veged/480490 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
// Continuation-passing style helper | |
var CPS = (function(){ | |
var slice = Array.prototype.slice, | |
slice1 = function(args) { return slice.call(args, 1) }, | |
cont = function(fn, args) { | |
args = slice1(args); | |
return function() { return fn.apply(null, args) } }; | |
return function(fn) { | |
cc = cont(fn, arguments); | |
if (this instanceof arguments.callee) while(cc = cc()); | |
else return cc; | |
}; | |
})(); | |
// Now can use 'return CPS(fn, [args])' for return continuation | |
function sum(n, cont) { | |
if (n == 0) return CPS(cont, 0); | |
return CPS(sum, n - 1, function(res) { return CPS(cont, n + res) }); | |
}; | |
// And 'new CPS(fn, [args])' for run your continuation-passing style function | |
new CPS(sum, 3000, function(res) { alert(res) }); | |
// Also read http://mihai.bazon.net/blog/redis-client-library-javascript-node | |
// ...and have fun ;-) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment