Last active
August 28, 2017 19:13
-
-
Save islam3zzat/64830ab56228cf7b8f8af4bd91d60b73 to your computer and use it in GitHub Desktop.
Tail calls elimination (ES6)
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
// Tail call optimization | |
// this function call itself n times | |
function f(x) { | |
// with every new call, new stack frame is created | |
// there is a limit, this limit varies from engine to another, but there is a limit | |
// this simple function breaks on chrome at f(100000) | |
if (x < 1) { | |
return 0 | |
} | |
return f(x -1) | |
} | |
// fortunately ES6, guarantee "no stack consumption" for function invocations in tail call positions. | |
// https://www.ecma-international.org/ecma-262/6.0/#sec-tail-position-calls | |
// https://kangax.github.io/compat-table/es6/#test-proper_tail_calls_(tail_call_optimisation) | |
//------------------ | |
// so by just adding 'use strict'; in engins that implemented this spec we get its binefits | |
function g(x) { | |
'use strict'; | |
// this simple function now works perfectly g(100000) | |
if (x < 1) { | |
return 0 | |
} | |
return g(x -1) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment