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
51 changes: 49 additions & 2 deletions src/arrayMethodSort.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,55 @@
* Implement method Sort
*/
function applyCustomSort() {
[].__proto__.sort2 = function(compareFunction) {
// write code here
[].__proto__.sort2 = function (compareFunction) {

Choose a reason for hiding this comment

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

You define [].__proto__.sort2 here, but the task requires implementing Array.prototype.sort using that predefined sort2. Add a delegation after sort2 is defined, for example:

Array.prototype.sort = function(compareFunction) {
  return this.sort2(compareFunction);
};

This will satisfy the requirement to implement Array.prototype.sort by using sort2.

if (
compareFunction !== undefined &&
typeof compareFunction !== 'function'
) {
throw new TypeError(
'The comparison function must be either a function or undefined',
);
}

const compare =
compareFunction ||
((a, b) => {
const s1 = String(a);
const s2 = String(b);

if (s1 < s2) {
return -1;
}

if (s1 > s2) {
return 1;
}

return 0;
});

const length = this.length;

for (let i = 0; i < length; i++) {

Choose a reason for hiding this comment

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

A small suggestion: using bubble sort is acceptable for this task (and you already added an early-exit optimization). If you want to improve performance later, consider using a faster algorithm (e.g., quicksort or mergesort) for large arrays.

let swapped = false;

for (let j = 0; j < length - 1 - i; j++) {
if (compare(this[j], this[j + 1]) > 0) {
[this[j], this[j + 1]] = [this[j + 1], this[j]];
swapped = true;
}
}

if (!swapped) {
break;
}
}

return this;
};

[].__proto__.sort = function (compareFunction) {
return this.sort2(compareFunction);
};
}

Expand Down