I think the algorithm implementation itself is reasonably efficient, but I'm not sure about proper use of good practices in software development in the code (variable naming, idioms, comments, error handling in inputs etc).
I'm attempting to get a first developer job, and since interviewers also evaluate how "clean" the code is, the main point of the question is what is considered good practice, but efficiency improvements are also welcome.
mergeSortedArrays = function(arr1, arr2){
if(!(Array.isArray(arr1) && Array.isArray(arr2))){
throw new TypeError("Need two arrays to merge")
};
if(arr2.length === 0 && arr1.length === 0){
throw new RangeError("Cannot merge empty arrays")
};
let i = 0;
let j = 0;
const targetSize = arr1.length + arr2.length;
const mergedArray = [];
// main loop
while(mergedArray.length < targetSize){
/**
* Works until completion for arrays of the same size
*/
if(arr1[i] < arr2[j]){
valueToPush = arr1[i]
i++
}else{
valueToPush = arr2[j]
j++
}
/**
* For arrays with different sizes, it is safe to push the remainder to the sorted array, given that both inputs are sorted.
*/
if(valueToPush === undefined){
const remainingItems = j > arr2.length ? arr1.slice(i) : arr2.slice(j)
mergedArray.push(...remainingItems)
break
}
mergedArray.push(valueToPush)
}
return mergedArray;
}
```
[1, 2, 3, undefined]
and had to work around it. The size of inputs issue is specific to this implementation, not to the problem itself. \$\endgroup\$ – Matheus Deister Veiga Mar 13 '20 at 14:40[1, 2]
then it does't matter if the second array is[]
,[3]
,[3, 4]
, or[3, 4, 5]
. Any reasonable algorithm would first place the elements1
and2
in the result array and then the elements of the seond array. The sizes of the arrays never play any role at all. \$\endgroup\$ – RoToRa Mar 16 '20 at 21:46