Created
March 28, 2018 00:32
-
-
Save corlaez/b0ab532626e3c36a697aeb16280611d6 to your computer and use it in GitHub Desktop.
Applying some ideas of http://matt.might.net/articles/by-example-continuation-passing-style/
This file contains 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 (CPS) | |
console.log('CPS factorial') | |
const CPS_fact = (n, callback = log) => { | |
console.log('CPS_fact push stack when n = '+ n) | |
if(n === 0) { | |
//console.log(`then we call callback$${n}(1)`) | |
callback(1)// executed when n is 0 | |
} else { | |
//console.log(`when n = ${n} then callback$${n - 1} = e => callback$${n}(e * ${n})`) | |
CPS_fact(n - 1, r => { | |
//console.log(`then we call callback$${n}(${r * n})`) | |
callback(r * n); | |
})// thanks to closure™ | |
} | |
console.log('CPS_fact pop stack when n = '+ n) | |
} | |
CPS_fact( | |
3, | |
r => console.log( | |
r + | |
' We get the result first' + | |
' and then we exit the stack' | |
) | |
) | |
console.log('') | |
console.log('Simple factorial') | |
const factorial = n => { | |
console.log('factorial push stack when n = '+ n) | |
const res = n === 0 ? 1 : n * factorial(n - 1) | |
console.log('factorial pop stack when n = '+ n) | |
return res | |
} | |
console.log( | |
factorial(3) + | |
' We have to wait to exit the stack' + | |
' to use the result' | |
) | |
// convenient default | |
function log(e) { | |
console.log(e) | |
} | |
// Uncomment the three lines in CPS factorial for more detail. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment