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
39 changes: 34 additions & 5 deletions src/arrayMethodSort.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,40 @@
'use strict';

/**
* Implement method Sort
*/
function defaultCompare(a, b) {
const first = String(a);
const second = String(b);

if (first < second) {
return -1;
}

if (first > second) {
return 1;
}

return 0;
}

function applyCustomSort() {
[].__proto__.sort2 = function(compareFunction) {
// write code here
[].__proto__.sort2 = function (compareFunction) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Consider adding an explicit type check for compareFunction so you throw a clear TypeError if a non-function is passed (the native Array.prototype.sort throws when compareFunction is provided but not a function). This check could go at the start of the function body before using compareFunction.

const isInvalidCompareFunction =
compareFunction !== undefined && typeof compareFunction !== 'function';

if (isInvalidCompareFunction) {
throw new TypeError('compareFunction must be a function');
}

const compare = compareFunction ?? defaultCompare;

for (let i = 0; i < this.length; 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.

Bubble sort is OK for this task, but it's O(n^2). For better performance on large arrays consider implementing a more efficient algorithm (quicksort/merge sort) or referencing the native sort for production code.

for (let j = 0; j < this.length - i - 1; j++) {
if (compare(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.

You assign the implementation to [].__proto__.sort2 but do not delegate Array.prototype.sort to it. The task requires that calls to arr.sort(...) run your custom logic (checklist items #1 and #8). Add a delegation after defining sort2, for example:

Array.prototype.sort = Array.prototype.sort2;

or

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

Place this after the sort2 assignment so arr.sort(...) uses your implementation.

};
}

Expand Down
Loading