I am solving Kolodny's Javascript exercises (here), specifically the 'value' exercise.
The problem requires me to create a function, fn where fn(value) will return an answer. If value is a scalar (i.e. 4), it will return 4.
If value is a function, it will return the return value of that function. If the value is a nested function, it will return the value of the deep-nested function. For example:
var fn = function() {
return function() {
return 4;
};
};
assert.equal(value(fn), 4);
I have solved the problem naively using the following:
exports.value = (val) => {
if (typeof val == 'function') {
if (typeof val() == 'function') {
if (typeof val()() =='function') {
if (typeof val()()() =='function') {
return false
} else {
return val()()();
}
} else {
return val()();
}
} else {
return val();
}
} else {
return val;
}
}
This code begs for reusability. Is there a way to use recursion to call n-number of deep-nested, anonymous functions?