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
33 changes: 31 additions & 2 deletions src/arrayMethodSort.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,37 @@
* Implement method Sort
*/
function applyCustomSort() {
[].__proto__.sort2 = function(compareFunction) {
// write code here
[].__proto__.sort2 = function (compareFunction) {
const callback =
compareFunction ||
((a, b) => {
const A = String(a);
const B = String(b);

if (A > B) {
return 1;
}

if (A < B) {
return -1;
}

return 0;
});

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

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 implementing Array.prototype.sort using the predefined [].__proto__.sort2. This file only defines sort2 but never assigns/implements sort to use it. Add an assignment after defining sort2, for example: [].__proto__.sort = [].__proto__.sort2; (or Array.prototype.sort = Array.prototype.sort2;) so Array.prototype.sort uses your implementation.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

After you define sort2, you need to make the built-in Array.prototype.sort use it. Add the wiring inside applyCustomSort (after the sort2 assignment). Example fixes:

  • Array.prototype.sort = Array.prototype.sort2;
    or
  • Array.prototype.sort = function(compareFunction) { return this.sort2(compareFunction); };
    Without this, calling arr.sort() will not use your custom logic and the task requirement is not satisfied.

};

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

Expand Down
Loading