Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save abhinavnigam2207/662fd6abd7e09216653d05622b976650 to your computer and use it in GitHub Desktop.
Save abhinavnigam2207/662fd6abd7e09216653d05622b976650 to your computer and use it in GitHub Desktop.
Recursive function to return the value returned by innermost function. (Asked in Wingify Interview)
function value(funcName) {
if(typeof funcName !== 'function') {
return funcName;
let func = funcName();
let resp = typeof func === 'function' ? value(func) : func;
return resp;
}
@abhinavnigam2207
Copy link
Author

Recursive function to return the value returned by innermost function. (Asked in Wingify Interview).
Example given below:

var scalar = 'foo';
var fn = function() { return 'bar'; };
var fn2 = function() {
  return fn;
};
var fn3 = function() {
  return fn2;
};
var innerPeace = function() {
  return function() {
    return function() {
      return function() {
        return function() {
          return function() {
            return function() {
              return function() {
                return function() {
                  return '42';
                };
              };
            };
          };
        };
      };
    };
  };
};

value(scalar);   // should be      'foo'
value(fn);          // should be      'bar'
value(fn2);        // should also be 'bar'
value(fn3);       // should also be 'bar'
value(innerPeace);     // should be '42'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment