Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions src/arrayMethodSort.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,21 @@
* Implement method Sort
*/
function applyCustomSort() {
[].__proto__.sort2 = function(compareFunction) {
// write code here
[].__proto__.sort2 = function (
compareFunction = (a, b) => String(a) > String(b),
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The default compareFunction is not correctly implemented. It should return a number (negative, 0, or positive) to be compliant with the Array.prototype.sort specification, but it returns a boolean. For example, sorting [10, 1] will not work as expected because '10' > '1' evaluates to false. A correct implementation could use String.prototype.localeCompare or explicit checks to return -1, 0, or 1.

) {
for (let i = 0; i < this.length - 1; i++) {
for (let j = 0; j < this.length - 1; j++) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This bubble sort implementation can be slightly optimized. After each full pass of the outer loop, the largest element for that pass is moved to its correct sorted position at the end of the unsorted portion of the array. Therefore, the inner loop doesn't need to check the elements that are already sorted. You can adjust the inner loop's condition to j < this.length - 1 - i.

if (compareFunction(this[j], this[j + 1]) > 0) {
const temp = this[j];

this[j] = this[j + 1];
this[j + 1] = temp;
}
}
}

return this;
};
}

Expand Down
Loading