-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Solution #2502
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Solution #2502
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,9 +4,37 @@ | |
| * Implement method Sort | ||
| */ | ||
| function applyCustomSort() { | ||
| [].__proto__.sort2 = function(compareFunction) { | ||
| // write code here | ||
| [].__proto__.sort2 = function (compareFunction = basicCompare) { | ||
| for (let i = 0; i < this.length - 1; i++) { | ||
| const elementToCompare1 = this[i]; | ||
| const elementToCompare2 = this[i + 1]; | ||
| const callback = compareFunction(elementToCompare1, elementToCompare2); | ||
|
|
||
| if (callback > 0) { | ||
| this[i] = elementToCompare2; | ||
| this[i + 1] = elementToCompare1; | ||
|
|
||
| i = -1; | ||
| } | ||
| } | ||
|
|
||
| return this; | ||
| }; | ||
|
|
||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The task requires that you implement |
||
| function basicCompare(a, b) { | ||
| const aLower = String(a).toLowerCase(); | ||
| const bLower = String(b).toLowerCase(); | ||
|
|
||
| if (aLower !== String(a) && bLower === String(b)) { | ||
| return -1; | ||
| } | ||
|
|
||
| if (bLower !== String(b) && aLower === String(a)) { | ||
| return 1; | ||
| } | ||
|
|
||
| return String(a).localeCompare(String(b)); | ||
|
Comment on lines
+28
to
+36
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The |
||
| } | ||
| } | ||
|
|
||
| module.exports = applyCustomSort; | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This loop implements a simple bubble/adjacent-swap sort by restarting the iteration (
i = -1) when a swap occurs. Using bubble sort is acceptable for this task, but consider recommending (or switching to) a more efficient algorithm (e.g., quicksort or mergesort) for larger arrays in real-world code.