Created
December 8, 2011 23:49
-
-
Save NV/1449309 to your computer and use it in GitHub Desktop.
Is it tail call or not?
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
function fact(x) { | |
return _f(1, x); | |
function _f(acc, x) { | |
return x === 0 ? | |
acc : | |
_f(acc * x, x - 1); | |
} | |
} | |
/* | |
Yes, it is! | |
fact(3) | |
_f(1, 3) => | |
_f(3, 2) => | |
_f(6, 1) => | |
6 | |
*/ | |
function inspectObj(obj) { | |
return _inspect('', obj); | |
function _inspect(accumulator, obj) { | |
switch(typeof obj) { | |
case 'object': | |
var keys = Object.keys(obj); | |
var length = keys.length; | |
if (length === 0) { | |
accumulator += '{}'; | |
} else { | |
accumulator += '{'; | |
for (var i = 0; i < length; i++) { | |
var key = keys[i]; | |
accumulator = _inspect(accumulator + key + ': ', obj[key]); | |
if (i < length - 1) { | |
accumulator += ', '; | |
} | |
} | |
accumulator += '}'; | |
} | |
break; | |
case 'string': | |
accumulator += JSON.stringify(obj); | |
break; | |
default: | |
accumulator += obj.toString(); | |
break; | |
} | |
return accumulator; | |
} | |
} | |
/* | |
No, it's not. | |
inspectObj({a: {b: {c: 1}}}) | |
_inspect('', {a: {b: {c: 1}}}) | |
_inspect('{a: ', {b: {c: 1}}) + '}' | |
_inspect('{a: {b: ', {c: 1}) + '}' + '}' | |
_inspect('{a: {b: {c: ', 1) + '}' + '}' + '}' | |
'{a: {b: {c: 1}}}' | |
How do I rewrite it using a tail call? | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment