4

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?

1 Answer 1

5
const value = v => typeof v === "function" ? value(v()) : v;

Just call value again with the result of the function.

A bit more readable:

function value(v) {
  if (typeof v === "function") {
    return value(v()); // !!!
  } else {
    return v;
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

When testing it, I get the error "value is not defined." I'm assuming because value exports an anonymous function? like so exports.value = (v) => {...}
@agomez yes, then do const value = exports.value = v => ...
that works great. I hadn't thought of exporting a value like that before, thanks. So that means "value" is set to an exports object, which returns an anonymous function, right? If so, wouldn't the notation to call it be value.exports()? Just wondering
@agomez no, it would be exports.value() otherwise :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.