styler
styler

Reputation: 16501

Improving conditional logic

I have a conditional statement that I'd like to improve on if possible as I find it quite unwieldy:

    let action

    if(options.add) {
        action = 'ADD'
    } else if(options.update) {
        action = 'UPDATE'
    } else {
        action = 'REMOVE'
    }

Is it possible to make this a switch or ternary of some sort?

Upvotes: 1

Views: 55

Answers (4)

Sreeragh A R
Sreeragh A R

Reputation: 3021

action = options.add && 'ADD' || options.update && 'UPDATE' || 'REMOVE'

Upvotes: 0

Nenad Vracar
Nenad Vracar

Reputation: 122087

If you want more dynamic solution you could create array of actions and then use find on that array to find that action in object and assign it to variable or set default value of REMOVE.

let action;
let options = {add: 1}
let actions = ['add', 'update', 'remove'];

action = (actions
  .find(a => options[a]) || 'remove')
  .toUpperCase();

console.log(action)

You can also make a function that will take options object and return action value.

let action;
var actions = ['add', 'update', 'remove'];

function setAction(options = {}) {
  return (actions.find(a => options[a]) || 'remove')
  .toUpperCase();
}

action = setAction({add: 1});
console.log(action)

action = setAction();
console.log(action)

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 122006

Your code looks ok to me now. But if you still looking for alternatives, Ternary ?

let action = options.add ? "ADD" :  (options.update ? "UPDATE" : "REMOVE") ;

Upvotes: 1

Mayank
Mayank

Reputation: 259

try this if you want ternary operation

let action;
action = (options.add) ? 'ADD' : ((options.update) ? 'UPDATE' : 'REMOVE');

Upvotes: 0

Related Questions