Skip to content
Open
Changes from 1 commit
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
15 changes: 13 additions & 2 deletions src/arrayMethodSort.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,19 @@
* Implement method Sort
*/
function applyCustomSort() {
[].__proto__.sort2 = function(compareFunction) {
// write code here
[].__proto__.sort2 = function (compareFunction) {
const callback =
compareFunction || ((a, b) => (String(a) > String(b) ? 1 : -1));
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 default comparator used here returns 1 when a > b and -1 otherwise, which also returns -1 when a and b are equal. Per the usual sort contract, the comparator should return 0 when values are equal. Consider adjusting to return 0 for equality, for example by checking < and > explicitly and returning 0 when neither is true.


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.

};
}

Expand Down
Loading