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

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

const compare = compareFunction || function (a, b) {
const sA = String(a);
const sB = String(b);
if (sA < sB) return -1;
if (sA > sB) return 1;
return 0;
}

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

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 and never adds/overrides Array.prototype.sort. Add a delegating implementation (for example: [].__proto__.sort = function(compareFunction) { return this.sort2(compareFunction); };) inside applyCustomSort() so the exported function installs both methods.

};

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

Expand Down