diff --git a/src/arrayMethodSort.js b/src/arrayMethodSort.js index 32363d0d..7bcb9b4e 100644 --- a/src/arrayMethodSort.js +++ b/src/arrayMethodSort.js @@ -1,12 +1,35 @@ -'use strict'; +"use strict"; /** * Implement method Sort */ function applyCustomSort() { - [].__proto__.sort2 = function(compareFunction) { + [].__proto__.sort2 = function (compareFunction) { // write code here + const callback = + typeof compareFunction === "function" + ? compareFunction + : (a, b) => + String(a).localeCompare(String(b), undefined, { + sensitivity: "case", + }); + + for (let i = this.length - 1; i > 0; i--) { + for (let j = 0; j < i; j++) { + if (callback(this[j], this[i]) > 0) { + swap(this, i, j); + } + } + } + + return this; }; } +function swap(arr, firstElementIndex, secondElementIndex) { + const tempPlaceHolder = arr[firstElementIndex]; + arr[firstElementIndex] = arr[secondElementIndex]; + arr[secondElementIndex] = tempPlaceHolder; +} + module.exports = applyCustomSort;