|
|
|
|
|
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");
}
|
|
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).
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: