Engineer Passion
Engineer Passion

Reputation: 1181

is there more elegant way to write this condition?

I want a smaller way to write this condition I've tried to simplify it but it doesn't work with me

if(( data.includes(userId) || data.includes(userId.toString())  || data.includes(username) )) console.log(true)

this condition works very good but I want a simplified version of it

Upvotes: 1

Views: 87

Answers (3)

Kitiara
Kitiara

Reputation: 498

Make flags using bitsets, such as this;

haveUserid = 1,
haveUsername = 2,
haveSchoolId = 4,
haveBadge = 8,
haveBlabla = 16,

Set the flag(let's say you want to set as haveUserid, haveUsername and haveBlabla)

data.flag = haveUserid + haveUsername + haveBlabla; // equals 1+2+8 = 11

and then you test the bits. I don't know if javascript has somekind of a function but you can also write a function of your own. That way you wouldn't have to write N amount of data.includes inside an if statement and just test the bits to see if data.flag satisfies your conditions.

Upvotes: 0

Slai
Slai

Reputation: 22886

If you define data as object instead of array, the condition can be simplified to:

if (data[userId] || data[username]) console.log(true)

Also, the check will be O(1) instead of O(n). Example:

var data = {1:1, '2':1}

if (data[1]) console.log(1)
if (data[2]) console.log(2)
if (data['2']) console.log("'2'")
if (data[3] || data[2]) console.log('3 or 2')

or Set:

var data = new Set([1, '2'])

if (data.has(1)) console.log(1)
if (data.has(2)) console.log(2) // false
if (data.has('2')) console.log("'2'")
if (data.has(3) || data.has(2) || data.has('2')) console.log('3 or 2')

Upvotes: 1

Bergi
Bergi

Reputation: 665286

You can use the some Array method to test for multiple predicates. Either

if ([userId, userId.toString(), username].some(x => data.includes(x))) …

or

if (data.some(x => [userId, userId.toString(), username].includes(x))) …

Upvotes: 5

Related Questions