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