Daniel Davies
Daniel Davies

Reputation: 51

Refactoring repeated ternary statements?

I'm reviewing PR's, and the author has a situation where they are using repeated ternaries, thus -

const foo = isConditionTrue ? 'foo' : '';
const bar = isConditionTrue ? 'bar' : '';
const baz = isConditionTrue ? 'baz' : '';

This seems repetitive but a better method doesn't immediately spring to mind. I've thought about assigning to an empty string and reassigning in an if block, but I don't feel that's any cleaner.

Any suggestions helpful, and thank you for your time.

Upvotes: 0

Views: 330

Answers (2)

Keith
Keith

Reputation: 24221

You could maybe use array destructoring..

const isConditionTrue = true;
const [foo,bar,baz] = isConditionTrue ? 
    ["foo", "bar","baz"] : ["","",""];
    
console.log(foo, bar, baz);
    
    

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386680

You could curry the problem and take a predefined function where you just insert the value for a true condition.

const setCondition = (condition, default) => value => condition ? value : default;

const checkCondition = setCondition(isConditionTrue, '');

const foo = checkCondition('foo');
const bar = checkCondition('bar');
const baz = checkCondition('baz');

Upvotes: 1

Related Questions