Cathal Cathal - 1 year ago 85
Javascript Question

return a string based on conditions without using if/else

I have an object something like

const myObj = {
hasError: true/false,
someProp: 'someValue'

Based on this object I have four conditions to evaluate:

  1. Object is empty

  2. hasError is true

  3. has error is false and someProp is undefined

  4. has error is false and some prop is defined

I'd like to find a nice and readable way to evaluate these 4 conditions without resorting to if/else.

Any ideas greatly appreciated.

Answer Source

Write the conditions and ensuing actions as an array of condition/action tuples:

const actions = [
  {if: o => !Object.keys(o).length, then: () => console.log("empty")},
  {if: o => o.hasError,             then: () => console.log("hasError")},
  {if: o => !o.someProp,            then: () => console.log("someProp is undefined")},
  {if: o => true,                   then: () => console.log("got everything")}

Now find the first matching condition and execute the associated logic:

actions.find(action => action.if(myObj)).then()

If it is not guaranteed that at least one condition will be satisfied, then you would need to check the result of the find to make sure it's not null.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download