Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 49 additions & 5 deletions src/arrayMethodSort.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,56 @@
'use strict';

/**
* Implement method Sort
*/
// Função que adiciona um método de ordenação customizado ao Array
function applyCustomSort() {
[].__proto__.sort2 = function(compareFunction) {
// write code here
// Função de comparação padrão
const defaultCompare = (a, b) => {
const stringA = a !== undefined ? String(a) : undefined;
const stringB = b !== undefined ? String(b) : undefined;

// Regras de comparação para valores undefined e strings
return stringA === undefined && stringB === undefined
? 0
: stringA === undefined
? 1
: stringB === undefined
? -1
: stringA > stringB
? 1
: stringA < stringB
? -1
: 0;
};

// Adiciona o método sort2 ao protótipo de Array
[].__proto__.sort2 = function (compareFunction = defaultCompare) {
const arr = this;
let item = arr[0];
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The item variable is initialized here with arr[0], but this initial value is never actually used. The variable is reassigned within the loop before it's used for swapping. To improve clarity and keep the variable's scope as narrow as possible, consider declaring it just before it's needed inside the loop.


// Valida se compareFunction é uma função ou undefined
if (
compareFunction !== undefined &&
typeof compareFunction !== 'function'
) {
throw new TypeError(
'A função de comparação deve ser uma função ou undefined',
);
}

// Algoritmo de ordenação simples (bubble sort adaptado)
for (let i = 0; i < arr.length - 1; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (compareFunction(arr[i], arr[j]) > 0) {
item = arr[i];
arr[i] = arr[j];
arr[j] = item;
}
}
}

// Retorna o array ordenado
return arr;
};
}

// Exporta a função para uso em outros arquivos
module.exports = applyCustomSort;
Loading