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
20 changes: 18 additions & 2 deletions src/arrayMethodSort.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,24 @@
* Implement method Sort
*/
function applyCustomSort() {
[].__proto__.sort2 = function(compareFunction) {
// write code here
[].__proto__.sort2 = function (compareFunction) {
// const newArray = [];
let compair = compareFunction;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

You have a small typo in the variable name here. It should be compare instead of compair. This typo is used consistently throughout the function, so be sure to correct it in all places.


if (typeof compair !== 'function') {
compair = (a, b) =>
String(a) > String(b) ? 1 : String(a) < String(b) ? -1 : 0;
}

for (let i = 0; i < this.length - 1; i++) {
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 implementation doesn't handle sparse arrays (arrays with empty slots) in the same way as the native Array.prototype.sort. The native method moves all empty slots to the end of the array, whereas your current logic treats them as undefined and includes them in the sorting comparison based on the string 'undefined'.

for (let j = i + 1; j < this.length; j++) {
if (compair(this[i], this[j]) > 0) {
[this[i], this[j]] = [this[j], this[i]];
}
}
}

return this;
};
}

Expand Down