Skip to content
Open
Changes from all commits
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
29 changes: 27 additions & 2 deletions src/arrayMethodSort.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,33 @@
* Implement method Sort
*/
function applyCustomSort() {
[].__proto__.sort2 = function(compareFunction) {
// write code here
[].__proto__.sort2 = function (compareFunction) {
const cmp =
compareFunction ??
function (s1, s2) {
if (s1 === null || s2 === undefined) {
return 1;
}
Comment on lines +11 to +13
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 condition doesn't correctly handle all cases for null and undefined values. For instance, cmp(5, undefined) will return 1, which means 5 is considered greater than undefined. This will cause undefined values to move to the beginning of the array, but they should be moved to the end. The logic needs to differentiate between s1 being nullish and s2 being nullish.


return s1?.toString() > s2?.toString()
? 1
: s1?.toString() < s2?.toString()
? -1
: 0;
};
Comment thread
AndreyKagaml marked this conversation as resolved.

for (let i = 0; i < this.length - 1; i++) {
for (let j = 0; j < this.length - 1 - i; j++) {
if (cmp(this[j], this[j + 1]) > 0) {
const item = this[j];

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

return this;
};
}

Expand Down