Skip to content

Instantly share code, notes, and snippets.

@codelahoma
Forked from adrusi/gist:1905351
Created June 16, 2013 22:55
Show Gist options
  • Save codelahoma/5793765 to your computer and use it in GitHub Desktop.
Save codelahoma/5793765 to your computer and use it in GitHub Desktop.
0
# 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