Skip to content

Instantly share code, notes, and snippets.

@derhuerst
Last active February 8, 2016 18:27
Show Gist options
  • Save derhuerst/e77d6179ac18243614fe to your computer and use it in GitHub Desktop.
Save derhuerst/e77d6179ac18243614fe to your computer and use it in GitHub Desktop.
`n + … + 0` in JS
sum = require './sum'
for name, fn of sum
start = Date.now()
i = 500000
while i > 0
n = fn 1000, 0
i--
end = Date.now()
console.log name, end - start
recursive 2817
tailCall 4337
normal 905
trampoline 5359
trampoline2 4104
recursive = (n) -> if n is 0 then 0 else n + recursive n - 1
tailCall = (n, acc) ->
if n is 0 then 0
else
acc += n--
tailCall n, acc
normal = (n) ->
v = 0
while n > 0
v += n--
return v
trampoline = (n) ->
acc = 0
iteratee = ->
acc += n
n--
iteratee
iteratee = iteratee() while n > 0
return acc
trampoline2 = (n) ->
acc = 0
iteratee = ->
acc += n--
undefined
iteratee() while n > 0
return acc
module.exports = {recursive, tailCall, normal, trampoline, trampoline2}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment