简体   繁体   中英

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.

You could maybe use array destructoring..

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

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM