0

Ternary over ternary is always difficult to write and understand.

some times I use this function:

 const a = polynary(a == 2, 'first', c == 3, 'second',
     x == y, 'third', (more any pairs), 
    'otherwise this/null if suppressed')

Javascript Version

function polynary(...booleanAndValues) {
    const size = booleanAndValues.length; 
    const isPair = (size % 2) === 0 
    let k = 0;
    while (k < (isPair?  size: size -1)) {
        if (booleanAndValues[k]) {
            return (booleanAndValues[k+1]);
        };
        k += 2;
    };
    return isPair ? null : booleanAndValues[size - 1];
};

The problem with this approach is that there is no shortcut for the expression/return evaluation, meaning that:

const a = polynary(softCondition, softReturn, heavyConsumerCondition, heavyConsumerReturn, evenHeavierReturn) would not be shortcutted if (softCondtion) and all the heavy useless operation would be processed.

So, useless if not for already in-memory variables.

I was wondering if with some currying/tasks like

expression = (parameter) => () => heavyDuty(parameter)

I could avoid processing all the parameters and if there is some magic in the functional programming side to tackle it.

This is not an important issue, just an opportunity to explore alternatives.

JLCDev
  • 609
  • 1
  • 5
  • 18
  • 3
    Ternary operator combination in JavaScript is not really that bad because unlike PHP the binding is correct. You can write `a ? b : c ? d : e ? f : g` and it works the way you'd expect. – Pointy Apr 19 '19 at 01:50
  • 1
    You can pass functions instead of evaluation the conditions: `polynary(() => heavyCondition, () => heavyReturn, ...);` It looks ugly, but the evaluation won't happen until the function is called (you can skip any of them) – ibrahim mahrir Apr 19 '19 at 02:10
  • BTW, yo could use spaces and newlines when using nested ternary operations to help clarifying them like in [this other SO question](https://stackoverflow.com/a/243349/9867451) – ibrahim mahrir Apr 19 '19 at 02:14

0 Answers0