JScript is not a natural support CPS, but a distribution engine can be written to work in CPS style. Generally there is only one active continuation, so you can define the rule: JScript CPS functions allow return, but the last thing they do must be the distribution engine that will continuation tell us.
To make things simple, we have one parameter for each CPS-style function, and of course, it can be an object that contains multiple fields.
Let's review the previous CPS treedepth program and replace all the continuation calls with one such call: This call tells the runtime engine what to do next continuation. The function can then return normally and have the runtime engine call continuation.
function Treedepth (args) { if (args.curtree = ) cont (args.afterdepth, 0 else { function Afterleft (leftdepth) { function Afterright (rightdepth) {cont (args.afterdepth,
1+math.max (Leftdepth, rightdepth)); } cont (treedepth, {curtree:args.curtree.right, afterdepth:afterright}); } cont (treedepth, {curtree:args.curtree.left, afterdepth:afterleft}); }}
distribution engine is
var continuation = null ; function Cont (NEWFUNC, Newargs) {continuation = {func: Newfunc, Args:newargs};} function run () { while (continuation! = null var curfunc = Continuation.func; var curargs = Continuation.args; Continuation = null ; Curfunc (Curargs); }}
If the next step does not need to be called, it means that the program is complete. To determine the depth of a tree, we simply tell continuation what the engine needs to do next.
Cont (treedepth, {curtree:mytree, afterdepth:print}); run ();
Original: https://blogs.msdn.microsoft.com/ericlippert/2005/08/15/recursion-part-six-making-cps-work/
Recursive--cps (iii)