Last active
February 8, 2016 18:27
-
-
Save derhuerst/e77d6179ac18243614fe to your computer and use it in GitHub Desktop.
`n + … + 0` in JS
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
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 |
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
recursive 2817 | |
tailCall 4337 | |
normal 905 | |
trampoline 5359 | |
trampoline2 4104 |
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
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