I’m just learning how to code and while studying sorting algorithms I was asked to “see if you can combine the two lines in your if and else blocks into one line to make your code look a little cleaner.”
const merge = (leftArray, rightArray) => {
const sortedArray = [];
while (leftArray.length > 0 && rightArray.length > 0) {
if (leftArray[0] < rightArray[0]) {
sortedArray.push(leftArray[0]);
leftArray.shift();
} else {
sortedArray.push(rightArray[0]);
rightArray.shift();
}
}
The first thing that came to my mind was to use ternary operator, and then, for some reason (never saw that being done before), I thought that I could just take the two actions for every condition, join them with ‘&&’ and that would work.
But I had a typo!! I wrote ‘&’ instead of ‘&&’, and for my surprise, even with that it worked as intended. But I have no idea why, can’t find anything that explains how this actually works and why. (Below is all the code and the part I re-wrote).
const mergeSort = (startArray) => {
const length = startArray.length;
if (length === 1) {
return startArray;
}
const mid = Math.floor(length / 2);
const leftArray = startArray.slice(0, mid);
const rightArray = startArray.slice(mid, length);
return merge(mergeSort(leftArray), mergeSort(rightArray))
}
const merge = (leftArray, rightArray) => {
const sortedArray = [];
while (leftArray.length > 0 & rightArray.length > 0) {
leftArray[0] < rightArray[0] ?
sortedArray.push(leftArray[0]) & leftArray.shift() :
sortedArray.push(rightArray[0]) & rightArray.shift()
}
return sortedArray.concat(leftArray).concat(rightArray);
}
I would appreciate if some could shed some light to this.