CPS
Continuation Passing Style (CPS)
function foo() {
bar(function(res) {
console.log("result = " + res);
});
}
function bar(fn) {
baz(fn);
}
function baz(fn) {
fn(3);
}
foo();
Last updated
function foo() {
bar(function(res) {
console.log("result = " + res);
});
}
function bar(fn) {
baz(fn);
}
function baz(fn) {
fn(3);
}
foo();
Last updated
// Synchronouse version
const a = 1;
const b = 2;
const c = 3;
const d = 4;
const e = 5;
const r = a + (Math.pow(b, 2) * c) / d - e; // -4
// CPS version
function mul(x, y, cont) {
cont(x * y);
}
function add(x, y, cont) {
cont(x + y);
}
function sub(x, y, cont) {
cont(x - y);
}
function div(x, y, cont) {
cont(x / y);
}
function sqr(x, cont) {
cont(x ^ 2);
}
sqr(b, function(res) {
mul(res, c, function(res) {
div(res, d, function(res) {
add(a, res, function(res) {
sub(res, e, function(res) {
console.log(res); // -4
});
});
});
});
});