Hacker News new | ask | show | jobs
by jlhawn 1127 days ago
In the "Use as a `do` expression" section, the example which uses `run` does not need the `else` cases and could be simplified:

  function doWork() {
    const x = run(() => {
      if (foo()) return f();
      if (bar()) return g();
      return h();
    });
  
    return x * 10;
  }
2 comments

Can also get rid of the `run` and move parens to simplify even further:

  function doWork() {
    const x = () => {
      if (foo()) return f();
      if (bar()) return g();
      return h();
    };
  
    return x() * 10;
  }
And a step further into the past, no need for a lambda - I find this clearer:

  function doWork() {
    function calcX() {
      if (foo()) return f();
      if (bar()) return g();
      return h();
    }

    return calcX() * 10;
  }
Where "calc" can be "gen[erate]" or "find" or at least more descriptive.
Well you definitely can do that to my somewhat contrived example that is loosely based off of an example from the `do` expression proposal, but I'm not sure its better.

Part of the beauty of `run` is that you don't have to declare and name a function `calcX`. In longer and more complex examples, declaring a function inline like this is potentially confusing because you don't get to see where it is used, whereas with `run` you assign the return value immediately to a variable.

But then there's mental overhead figuring out / remembering what the function does every time you go through the parent function. Once you have it in your head, may as well just label it so you don't have to do that every time.

> In longer and more complex examples, declaring a function inline like this is potentially confusing because you don't get to see where it is used

It only exists in the scope of the parent function, the only place it can be used is right next to where is declared. Unless you're in the habit of making functions hundreds of lines long, I guess...

Presumably this is a simplified example and "x" is intended to be used more than once?
Completely agreed, and I use this if-based early return syntax frequently! That being said, I like using `if` and `else if` and `else`, but maybe that's just me! I don't think there's a substantial difference in readability or utility.