Skip to content

Instantly share code, notes, and snippets.

@vhf

vhf/tail-call.js Secret

Created Nov 2, 2015
Embed
What would you like to do?
// file: tail-call.js
// "naive"
function factorial1(x) {
if (x <= 0) {
return 1;
} else {
return x * factorial1(x-1);
}
}
// tail rec using a default parameter
function factorial2(n) {
return facRec2(n);
}
function facRec2(x, acc = 1) {
if (x <= 1) {
return acc;
} else {
return facRec2(x-1, x*acc);
}
}
// tail rec
function factorial3(n) {
return facRec3(n, 1);
}
function facRec3(x, acc) {
if (x <= 1) {
return acc;
} else {
return facRec3(x-1, x*acc);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment