Home > Back-end >  Conditionally rendering an Array Method using Ternary Operator
Conditionally rendering an Array Method using Ternary Operator

Time:10-22

This is a strange situation but utilizing the ternary operator to determine my array method would allow for much dryer code.

The goal:

const result = array. (isTrue ? some : every) (item) => {A lot of logic}

The above code obviously wont work but I wanted to see if there was some syntax that would allow something like this?

CodePudding user response:

You can use the bracket notation to access the method conditionally:

const method = (isTrue, array) => array[isTrue ? 'some' : 'every'](item => item)

const arr = [0, 1, 2]

console.log(method(true, arr)) 
console.log(method(false, arr))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

I'd just do it this way:

const myLogic = (item) => { a lot of logic };

const result = isTrue ? array.some(myLogic) : array.every(myLogic)
  • Related