-
-
Save codelahoma/5793765 to your computer and use it in GitHub Desktop.
0
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
# moved internal properties to arguments.callee so | |
# we don't have to worry about name collisions with our | |
# context. | |
tco = (fn) -> | |
(args...) -> | |
my = arguments.callee | |
my.recurred = false | |
my.args = [] | |
my.recur = (args...) => | |
my.recurred = true | |
my.args = args | |
returnVal = fn.apply this, args | |
while true | |
if my.recurred | |
tempArgs = my.args | |
my.args = undefined | |
my.recurred = false | |
returnVal = fn.apply this, tempArgs | |
else | |
return returnVal | |
#============================================== | |
factorial = tco (n, acc = 1) -> | |
if n is 0 | |
acc | |
else | |
factorial.recur n - 1, acc * n | |
console.log factorial 100000 | |
#============================================== | |
console.log factorial 60 | |
factorialWithCtx = tco (n, acc = 1) -> | |
if n is 0 | |
acc | |
else | |
@iterations++ | |
factorialWithCtx.recur n - 1, acc * n | |
counter = | |
iterations: 0 | |
console.log factorialWithCtx.call counter, 100000 | |
console.log counter.iterations |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment