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
32 changes: 30 additions & 2 deletions src/arrayMethodSort.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,37 @@
* Implement method Sort
*/
function applyCustomSort() {
[].__proto__.sort2 = function(compareFunction) {
// write code here
[].__proto__.sort2 = function (compareFunction = basicCompare) {
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 loop implements a simple bubble/adjacent-swap sort by restarting the iteration (i = -1) when a swap occurs. Using bubble sort is acceptable for this task, but consider recommending (or switching to) a more efficient algorithm (e.g., quicksort or mergesort) for larger arrays in real-world code.

const elementToCompare1 = this[i];
const elementToCompare2 = this[i + 1];
const callback = compareFunction(elementToCompare1, elementToCompare2);

if (callback > 0) {
this[i] = elementToCompare2;
this[i + 1] = elementToCompare1;

i = -1;
}
}

return this;
};

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 task requires that you implement Array.prototype.sort using the predefined [].__proto__.sort2. This file defines sort2 but never assigns/implements Array.prototype.sort. Add something like Array.prototype.sort = [].__proto__.sort2; or Array.prototype.sort = function(compare) { return this.sort2(compare); }; after the sort2 definition so the built-in sort is replaced by your implementation.

function basicCompare(a, b) {
const aLower = String(a).toLowerCase();
const bLower = String(b).toLowerCase();

if (aLower !== String(a) && bLower === String(b)) {
return -1;
}

if (bLower !== String(b) && aLower === String(a)) {
return 1;
}

return String(a).localeCompare(String(b));
Comment on lines +28 to +36
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 basicCompare function tries to prefer values with uppercase letters by using aLower !== String(a) checks. This is a bit unconventional and may behave unexpectedly for non-string items. If the goal is case-insensitive comparison, consider simply using String(a).localeCompare(String(b), undefined, { sensitivity: 'base' }) or document the intended tie-breaking behavior clearly.

}
}

module.exports = applyCustomSort;
Loading