Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SPOILERS] Regarding value solution #48

Closed
zg opened this issue Sep 4, 2016 · 3 comments
Closed

[SPOILERS] Regarding value solution #48

zg opened this issue Sep 4, 2016 · 3 comments

Comments

@zg
Copy link

zg commented Sep 4, 2016

Theoretically wouldn't you hit a stack overflow if you used a recursive approach to the value exercise?

@kolodny
Copy link
Owner

kolodny commented Sep 5, 2016

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.

@kolodny kolodny closed this as completed Sep 5, 2016
@zg
Copy link
Author

zg commented Sep 5, 2016

This doesn't hang and it also passed all tests:

module.exports = value;

function value(val) {
  while(typeof val === 'function')
    val = val();
  return val;
}

@kolodny
Copy link
Owner

kolodny commented Sep 5, 2016

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants