JavaScript developers frequently need to apply different logical operators based on runtime conditions. This pattern appears regularly in form validation, permission systems, feature flags, and API handling, but currently requires verbose code:
There's some languages out there where you can treat operators as functions by wrapping them in parentheses. If JavaScript were to support something like that, it could help solve your specific problem, and other similar problems.
const result = (ascending ? (<) : (>))(value, threshold);
(We conditionally decide if we want the less than or greater than function, then we call it with the two operands).
Alternatively, we could follow in Pythonβs footsteps - they don't let you convert an operator into a function per-say, but they do provide a module containing all built-in operators as functions.
Just a couple of other ways I can think of to solve the stated problem.
In my opinion, this drastically decreases readability. Things getting shorter is not an improvement if it makes the logic harder to parse. Just write the conditional, it makes it clear exactly whatβs going on.
JavaScript developers frequently need to apply different logical operators based on runtime conditions. This pattern appears regularly in form validation, permission systems, feature flags, and API handling, but currently requires verbose code:
This is typically solved with the strategy
pattern, especially
since it's not always just logical operators.
Your examples should be written as
const strategy = field.isRequired
? v => v && v.length > 0
: v => !v || v.length > 0;
const isValid = strategy(field.value);
Btw, in your first example, if field.value is a string (or even a
string-or-undefined) then (!field.value || field.value.length > 0) is
always true. You can therefore simplify the statement to just