From 41fa3fec7cc3c4d713235fb812a6764bf3403b93 Mon Sep 17 00:00:00 2001 From: Kaio Kampos Date: Wed, 28 Jan 2026 11:38:44 -0300 Subject: [PATCH] Solution --- src/arrayMethodSort.js | 39 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/src/arrayMethodSort.js b/src/arrayMethodSort.js index 32363d0d..e947a6e8 100644 --- a/src/arrayMethodSort.js +++ b/src/arrayMethodSort.js @@ -4,8 +4,43 @@ * Implement method Sort */ function applyCustomSort() { - [].__proto__.sort2 = function(compareFunction) { - // write code here + [].__proto__.sort2 = function (compareFunction) { + let compareFn = compareFunction; + const arr = this; + const length = arr.length; + + // Se não houver compareFn, usamos o comportamento padrão + if (typeof compareFn !== 'function') { + compareFn = function (a, b) { + const strA = String(a); + const strB = String(b); + + if (strA < strB) { + return -1; + } + + if (strA > strB) { + return 1; + } + + return 0; + }; + } + + // Bubble Sort + for (let i = 0; i < length - 1; i++) { + for (let j = 0; j < length - 1 - i; j++) { + if (compareFn(arr[j], arr[j + 1]) > 0) { + // swap manual + const temp = arr[j]; + + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + } + } + } + + return arr; }; }