diff --git a/src/arrayMethodSort.js b/src/arrayMethodSort.js index 32363d0d..9968d6a6 100644 --- a/src/arrayMethodSort.js +++ b/src/arrayMethodSort.js @@ -4,9 +4,43 @@ * Implement method Sort */ function applyCustomSort() { - [].__proto__.sort2 = function(compareFunction) { - // write code here + [].__proto__.sort2 = function (compareFunction) { + const cmp = + compareFunction || + function (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 - 1; i++) { + for (let j = 0; j < this.length - i - 1; j++) { + if (cmp(this[j], this[j + 1]) > 0) { + const temp = this[j]; + + this[j] = this[j + 1]; + this[j + 1] = temp; + } + } + } + + return this; + }; + + /* eslint-disable no-extend-native */ + Array.prototype.sort = function (compareFn) { + return this.sort2(compareFn); }; + /* eslint-enable no-extend-native */ } module.exports = applyCustomSort;