An efficient version:
function includesTwo(array, one, two) {
let achou = false;
for (const item of array) {
if (item == one || item == two) {
if (achou) return true;
achou = true;
}
}
return false;
}
const a = ['view', 'edit', 'insert'];
console.log(includesTwo(a, 'view', 'edit'));
console.log(includesTwo(a, 'view', 'teste'));
I put in the Github for future reference.
This shape sweeps the array only once, in addition to being more efficient for using fewer abstractions, but that part isn’t important. When you send an item to be searched in a array once and then again may have spent doubled. So it is scanning once and find the two dice at once. Make no mistake includes()
and every()
is a for
abstracted, it has to sweep, potentially, the entire collection.
There is a detail that cannot have repeated values in array. If that can’t be guaranteed it gets a little more complicated:
function includesTwo(array, one, two) {
let achouOne = false;
let achouTwo = false;
for (const item of array) {
if (item == one) {
if (achouTwo) return true;
achouOne = true;
}
if (item == two) {
if (achouOne) return true;
achouTwo = true;
}
}
return false;
}
const a = ['view', 'view', 'edit'];
console.log(includesTwo(a, 'view', 'edit'));
console.log(includesTwo(a, 'view', 'teste'));
I put in the Github for future reference.
Can generalize to several items if you want, I did what the question asked. To do for any number of items would have to have a loop running through the values to be searched. The more items are added the greater the distance of the efficiency. With two values to be concatenated in the search the gain is good, since it can reduce the cost by half, but in a list of large values the gain can be absurdly large, including the use of includes()
and every()
can become unviable already has exponential complexity in relation to the values sought, while the solution of the simple loop I gave has linear complexity in relation to the values.
The path of the stones was given in the last one. You need a control variable for each value you search for. How to do this if you can have multiple values? Simple, put in a collection. You can use a array with the key being each value starting in false
and changing true
when you find that.
Nothing better than good, old and guaranteed IF() well used. Congratulations, from my point of view your first code
arr.includes('view') && arr.includes('test')
solves, is what it should always be, without exaggerating and without creating methodologies or else find that ES6 onwards will change 100% of the language. Live the simple that works well :D (ps: for backward compatibility I suggest theindexOf() !== 1
)– Guilherme Nascimento