diff --git a/src/arrayMethodSort.js b/src/arrayMethodSort.js index 32363d0d..8fa9e21c 100644 --- a/src/arrayMethodSort.js +++ b/src/arrayMethodSort.js @@ -4,8 +4,37 @@ * Implement method Sort */ function applyCustomSort() { - [].__proto__.sort2 = function(compareFunction) { - // write code here + [].__proto__.sort2 = function (compareFunction) { + const callback = + compareFunction || + ((a, b) => { + const A = String(a); + const B = String(b); + + if (A > B) { + return 1; + } + + if (A < B) { + return -1; + } + + return 0; + }); + + for (let i = 0; i < this.length - 1; i++) { + for (let j = 0; j < this.length - i - 1; j++) { + if (callback(this[j], this[j + 1]) > 0) { + [this[j], this[j + 1]] = [this[j + 1], this[j]]; + } + } + } + + return this; + }; + + [].__proto__.sort = function (compareFunction) { + return this.sort2(compareFunction); }; }