diff --git a/src/arrayMethodSort.js b/src/arrayMethodSort.js index 32363d0d..96f22e77 100644 --- a/src/arrayMethodSort.js +++ b/src/arrayMethodSort.js @@ -4,8 +4,39 @@ * Implement method Sort */ function applyCustomSort() { - [].__proto__.sort2 = function(compareFunction) { - // write code here + [].__proto__.sort2 = function (compareFunction) { + const defaultCompareFunction = (a, b) => { + const strA = String(a); + const strB = String(b); + + if (strA < strB) { + return -1; + } + + if (strA > strB) { + return 1; + } + + return 0; + }; + + let compare; + + if (typeof compareFunction === 'function') { + compare = compareFunction; + } else { + compare = defaultCompareFunction; + } + + for (let i = 0; i < this.length; i++) { + for (let j = 0; j < this.length - 1; j++) { + if (compare(this[j], this[j + 1]) > 0) { + [this[j], this[j + 1]] = [this[j + 1], this[j]]; + } + } + } + + return this; }; }