From 1dc987ee1d08a2db54f75b96442bbd9dbe77682a Mon Sep 17 00:00:00 2001 From: Banderos14 Date: Sat, 7 Mar 2026 12:36:17 +0100 Subject: [PATCH 1/2] feat: task_solution --- src/arrayMethodSort.js | 37 +++++++++++++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/src/arrayMethodSort.js b/src/arrayMethodSort.js index 32363d0d..f524a5e5 100644 --- a/src/arrayMethodSort.js +++ b/src/arrayMethodSort.js @@ -4,8 +4,41 @@ * Implement method Sort */ function applyCustomSort() { - [].__proto__.sort2 = function(compareFunction) { - // write code here + Array.prototype.sort2 = function (compareFunction) { + const compare = + typeof compareFunction === 'function' + ? compareFunction + : (a, b) => { + const left = String(a); + const right = String(b); + + if (left > right) { + return 1; + } + + if (left < right) { + return -1; + } + + return 0; + }; + + for (let i = 0; i < this.length; i++) { + for (let j = 0; j < this.length - 1 - i; j++) { + const a = this[j]; + const b = this[j + 1]; + + // Вызываем колбэк сравнения + // Если результат > 0, значит 'a' должно идти после 'b' + if (compare(a, b) > 0) { + // Меняем элементы местами (деструктуризация) + this[j] = b; + this[j + 1] = a; + } + } + } + + return this; }; } From 0f8affefc51f516f1391a0902e341f9cb609a7e5 Mon Sep 17 00:00:00 2001 From: Banderos14 Date: Sat, 7 Mar 2026 12:45:06 +0100 Subject: [PATCH 2/2] fix: rewrite methode) --- src/arrayMethodSort.js | 60 ++++++++++++++++++++---------------------- 1 file changed, 28 insertions(+), 32 deletions(-) diff --git a/src/arrayMethodSort.js b/src/arrayMethodSort.js index f524a5e5..20bc210f 100644 --- a/src/arrayMethodSort.js +++ b/src/arrayMethodSort.js @@ -4,41 +4,37 @@ * Implement method Sort */ function applyCustomSort() { - Array.prototype.sort2 = function (compareFunction) { - const compare = - typeof compareFunction === 'function' - ? compareFunction - : (a, b) => { - const left = String(a); - const right = String(b); - - if (left > right) { - return 1; - } - - if (left < right) { - return -1; - } - - return 0; - }; - - for (let i = 0; i < this.length; i++) { - for (let j = 0; j < this.length - 1 - i; j++) { - const a = this[j]; - const b = this[j + 1]; - - // Вызываем колбэк сравнения - // Если результат > 0, значит 'a' должно идти после 'b' - if (compare(a, b) > 0) { - // Меняем элементы местами (деструктуризация) - this[j] = b; - this[j + 1] = a; - } + [].__proto__.sort2 = function (compareFunction) { + const arr = this; + const func = (a, b) => { + const A = String(a); + const B = String(b); + + if (A < B) { + return -1; } + + if (A > B) { + return 1; + } + + return 0; + }; + + const cmp = typeof compareFunction === 'function' ? compareFunction : func; + + for (let i = 1; i < arr.length; i++) { + const next = arr[i]; + let prevIdx = i - 1; + + while (prevIdx >= 0 && cmp(arr[prevIdx], next) > 0) { + arr[prevIdx + 1] = arr[prevIdx]; + prevIdx--; + } + arr[prevIdx + 1] = next; } - return this; + return arr; }; }