Although your code seems to work, it is difficult to read. Loops inside loops and many if
, else if
blocks and continue
or return
. Let's start with some big issues:
You use an endless while loop when it is clear you don't have to. The code below would perform the same function:
function searchThreeSameNum(arr1, arr2, arr3) {
let i = 0, j = 0;
while (i < arr1.length && j < arr2.length) {
if (arr1[i] < arr2[j]) {
i++;
continue;
} else if (arr1[i] > arr2[j]) {
j++;
continue;
} else if (arr1[i] == arr2[j]) {
for (let k = 0; k < arr3.length; k++) {
if (arr1[i] == arr3[k]) return arr1[i];
}
}
}
return 'No equal numbers';
}
This has one less return 'No equal numbers';
(code repetition) and only one return
from within the while loop.
Now let's look at what the loop is actually doing. It runs through array 1 and 2 and tries to find equal pairs of values in them. If a pair is found it searches in the third array for the same value and returns it when it is found.
There is a handy array method called includes(). It could replace the whole looping of the third array, like this:
function searchThreeSameNum(arr1, arr2, arr3) {
let i = 0, j = 0;
while (i < arr1.length && j < arr2.length) {
if (arr1[i] < arr2[j]) {
i++;
continue;
} else if (arr1[i] > arr2[j]) {
j++;
continue;
} else if (arr1[i] == arr2[j]) {
if (arr3.includes(arr1[i])) return arr1[i];
}
}
return 'No equal numbers';
}
I could even go a step further and get rid of the while loop altogether by looping through array 1 and see if its values are contained in array 2 and 3, like this:
function searchThreeSameNum2(arr1, arr2, arr3) {
for (number of arr1) {
if (arr2.includes(number) && arr3.includes(number)) return number;
}
return 'No equal numbers';
}
Note that this simplification makes this function easy to read, but also less efficient. It has to checks array 2 and 3 completely, for every element of array 1, until a match is found.
The assumption, in the function above, is that array 1 is properly sorted. If it isn't you can sort it.
function searchThreeSameNum2(arr1, arr2, arr3) {
let sorted = arr1.sort((a, b) => a - b);
for (number of sorted) {
if (arr2.includes(number) && arr3.includes(number)) return number;
}
return 'No equal numbers';
}
Arrays 2 and 3 don't need to be sorted.
In summary
- If you use a while loop, always break the loop with a proper condition in the right place. Do not use endless loops.
- Try not to use complex execution flow constructions, with lot of
else
, continue
and return
. They are difficult to read and to debug.
- Use the build in array methods, they are very handy, but don't overdo it.
Set
API in ECMAScript is. \$\endgroup\$