From c738b03465275a14f3f72eb8b31298649cad69c1 Mon Sep 17 00:00:00 2001 From: Artem Date: Tue, 3 Feb 2026 14:53:17 +0200 Subject: [PATCH 1/2] Solution --- src/arrayMethodSort.js | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/src/arrayMethodSort.js b/src/arrayMethodSort.js index 32363d0d..61e34abc 100644 --- a/src/arrayMethodSort.js +++ b/src/arrayMethodSort.js @@ -4,8 +4,25 @@ * Implement method Sort */ function applyCustomSort() { - [].__proto__.sort2 = function(compareFunction) { - // write code here + [].__proto__.sort2 = function (compareFunction) { + const arr = this; + const len = arr.length; + + // Simple bubble sort implementation + for (let i = 0; i < len - 1; i++) { + for (let j = 0; j < len - i - 1; j++) { + const shouldSwap = compareFunction + ? compareFunction(arr[j], arr[j + 1]) > 0 + : String(arr[j]) > String(arr[j + 1]); + + if (shouldSwap) { + // Swap arr[j] and arr[j + 1] + [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]; + } + } + } + + return arr; }; } From 3b6af6f2ee19820cd6ac8430080b0b9efea2da9a Mon Sep 17 00:00:00 2001 From: Artem Date: Tue, 3 Feb 2026 15:03:40 +0200 Subject: [PATCH 2/2] Solution --- src/arrayMethodSort.js | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/src/arrayMethodSort.js b/src/arrayMethodSort.js index 61e34abc..d2b25a38 100644 --- a/src/arrayMethodSort.js +++ b/src/arrayMethodSort.js @@ -8,15 +8,27 @@ function applyCustomSort() { const arr = this; const len = arr.length; - // Simple bubble sort implementation for (let i = 0; i < len - 1; i++) { for (let j = 0; j < len - i - 1; j++) { - const shouldSwap = compareFunction - ? compareFunction(arr[j], arr[j + 1]) > 0 - : String(arr[j]) > String(arr[j + 1]); + const a = arr[j]; + const b = arr[j + 1]; + let shouldSwap = false; + + if (a === undefined && b === undefined) { + shouldSwap = false; + } else if (a === undefined) { + shouldSwap = true; + } else if (b === undefined) { + shouldSwap = false; + } else { + if (compareFunction) { + shouldSwap = compareFunction(a, b) > 0; + } else { + shouldSwap = String(a) > String(b); + } + } if (shouldSwap) { - // Swap arr[j] and arr[j + 1] [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]; } }