Skip to content

Instantly share code, notes, and snippets.

@islam3zzat
Last active August 28, 2017 19:13
Show Gist options
  • Save islam3zzat/64830ab56228cf7b8f8af4bd91d60b73 to your computer and use it in GitHub Desktop.
Save islam3zzat/64830ab56228cf7b8f8af4bd91d60b73 to your computer and use it in GitHub Desktop.
Tail calls elimination (ES6)
// 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