Hacker News new | ask | show | jobs
by mrighele 1060 days ago
If you want the equivalent of if-expression in JS, I think it is much better to make a separate function with a number of returns. In this case the function is already there:

  function deriv(exp, variable) {
    if (is_number(exp)) {
      return 0;
    }
    if (is_variable(exp)) {
      if (is_same_variable(exp, variable)) {
        return 1;
      } else {
        return 0;
      }
    }
    if (is_sum(exp)) {
      return make_sum(deriv(addend(exp), variable),
          deriv(augend(exp), variable));
    }
    if (is_product(exp)) {
      return make_product(deriv(multiplier(exp),
              variable),
          multiplicand(exp)))
    }
    return error(exp, "unknown expression type -- deriv");
  }
3 comments

It's subjective, but seconded (switch statements are also great for this because they make fall-through logic more obvious).

I'll add a couple of things onto this: early returns are very helpful for me in avoiding nesting if statements (although that's less applicable in this specific example).

  function op(cond) {
    if (cond) {
      //do something
    }
  }

  function op (cond) {
    if (!cond) { return; }
    //do something
  }
And it's good to remember that you can basically stick functions anywhere including inline, so it's not necessarily a requirement to take a function like this and move it to a top level as a private function. If you're only using it in one place you can just define it and call it anonymously.

And don't be afraid to still use ternary operators non-nested. There's a sibling comment complaining about the nested if statement. If that really bothers you, you can still do:

   if (is_variable(exp)) {
      return is_same_variable(exp, variable) ? 1 : 0;
   }
Refreshing to see some love for early return. Often people like to say they are an anti pattern, but then you have to maintain each layer of if nesting in your head (as they are sometimes off screen) when reasoning about code in the middle instead of handling edge cases first and leaving the rest of the method for the core/common case.

  if (is_same_variable(exp, variable)) {
    return 1;
  } else {
    return 0;
  }
should be

   return +is_same_variable(exp, variable)
Yeah, though might want to use Number(is_same_variable(..)) for additional clarity.
Get rid of the else in the is_variable(exp) block and this is a lot more readable than the nested ternary version and seems just as easy to transcode from Scheme. Darn.