Skip to content
Open
Changes from 2 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
21 changes: 19 additions & 2 deletions src/arrayMethodSort.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,25 @@
* Implement method Sort
*/
function applyCustomSort() {
[].__proto__.sort2 = function(compareFunction) {
// write code here
[].__proto__.sort2 = function (compareFunction) {
let cmp = compareFunction;

if (typeof cmp !== 'function') {
cmp = (a, b) => `${a}` > `${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.

Great progress on fixing the sorting logic! However, the compareFunction is still returning a boolean (true/false) instead of a number as required by the sort method's specification. A proper compare function must return a positive number, a negative number, or zero. While this works in your if statement due to type coercion, it doesn't fully replicate the native sort behavior. Please adjust this to return a numeric value, for example by using String.prototype.localeCompare().

}

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 temp = this[j];

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

return this;
};
}

Expand Down
Loading