Closed zg closed 8 years ago
That would be correct if the argument passed in always returned functions which isn't something that the function handles.
function value(val) {
if (typeof val === 'function') return value(val());
return val;
}
var fn = function() { return fn; };
value(fn); // stackoverflow
Using an iterative approach would just cause this to hang:
function value(val) {
var current = val;
while (typeof current === 'function') current = current();
return current;
}
var fn = function() { return fn; };
value(fn); // hangs, run at your own risk
You may think there's an argument to make for the recursive approach since you can have a try-catch
block around it if it is an invalid input, but for the same price you can have a loop counter in the iterative approach and throw once it breaks a threshold.
Let me know if there's anything I missed or misunderstood, and I'll reopen this issue.
This doesn't hang and it also passed all tests:
module.exports = value;
function value(val) {
while(typeof val === 'function')
val = val();
return val;
}
Sure. so does this
module.exports = value;
function value(thing) {
return typeof thing === 'function' ? value(thing()) : thing;
}
It doesn't cause a stack overflow because it has an termination condition
Theoretically wouldn't you hit a stack overflow if you used a recursive approach to the value exercise?