Skip to content
Draft
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
51 changes: 50 additions & 1 deletion src/arrayMethodSort.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,57 @@
* Implement method Sort
*/
function applyCustomSort() {
[].__proto__.sort2 = function(compareFunction) {
[].__proto__.sort2 = function (compareFunction) {
// write code here
const length = this.length;
const array = this;

let compare;

if (typeof compareFunction === 'function') {
compare = compareFunction;
} else {
compare = (a, b) => {
const aStr = String(a);
const bStr = String(b);

if (aStr < bStr) {
return -1;
} else if (aStr > bStr) {
return 1;
} else {
return 0;
}
};
}

for (let i = 0; i < length - 1; i++) {
for (let j = 0; j < length - i - 1; j++) {
const a = array[j];
const b = array[j + 1];

if (a === undefined && b !== undefined) {
array[j] = b;
array[j + 1] = a;
continue;
}

if (a !== undefined && b === undefined) {
continue;
}

if (a === undefined && b === undefined) {
continue;
}

if (compare(a, b) > 0) {
array[j] = b;
array[j + 1] = a;
}
}
}

return array;
};
}

Expand Down