tco
Version:
Tail call optimization in Node
48 lines (42 loc) • 1.57 kB
JavaScript
;
module.exports = tco;
function tco(f) {
console.log('enter tco fun'); // XXX
if (typeof f == 'function') {
var tf = function () {
console.log('D enter tf fun'); // XXX
var nf = f, na = arguments, next = true;
while (next) {
console.log(nf);
console.log('D start while block'); // XXX
next = false; console.log('D1'); // XXX
var r = nf.apply(null, na); console.log('D2'); // XXX
console.log('function applied'); // XXX
console.log('function returned: '); // XXX
console.dir(r); // XXX
if (typeof r[0] == 'function') {
if (typeof r[0].tco == 'function') {
nf = r[0].tco;
na = r[1];
next = true;
console.log('D1');
} else {
console.log('normal func');
throw 1;
return r[0].apply(null, r[1]);
}
} else if (r[0] == 'undefined') {
return r[1];
} else {
throw new Error('tco: bad value returned from a function');
}
console.log('D end while block'); // XXX
}
console.log('D while ended'); // XXX
};
tf.tco = f;
return tf;
} else {
throw new Error('tco() expects a function');
}
}