-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Implement custom sort method #2501
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?
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 |
|---|---|---|
| @@ -1,11 +1,40 @@ | ||
| 'use strict'; | ||
|
|
||
| /** | ||
| * Implement method Sort | ||
| */ | ||
| function defaultCompare(a, b) { | ||
| const first = String(a); | ||
| const second = String(b); | ||
|
|
||
| if (first < second) { | ||
| return -1; | ||
| } | ||
|
|
||
| if (first > second) { | ||
| return 1; | ||
| } | ||
|
|
||
| return 0; | ||
| } | ||
|
|
||
| function applyCustomSort() { | ||
| [].__proto__.sort2 = function(compareFunction) { | ||
| // write code here | ||
| [].__proto__.sort2 = function (compareFunction) { | ||
| const isInvalidCompareFunction = | ||
| compareFunction !== undefined && typeof compareFunction !== 'function'; | ||
|
|
||
| if (isInvalidCompareFunction) { | ||
| throw new TypeError('compareFunction must be a function'); | ||
| } | ||
|
|
||
| const compare = compareFunction ?? defaultCompare; | ||
|
|
||
| for (let i = 0; i < this.length; i++) { | ||
|
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. Bubble sort is OK for this task, but it's O(n^2). For better performance on large arrays consider implementing a more efficient algorithm (quicksort/merge sort) or referencing the native sort for production code. |
||
| for (let j = 0; j < this.length - i - 1; j++) { | ||
| if (compare(this[j], this[j + 1]) > 0) { | ||
| [this[j], this[j + 1]] = [this[j + 1], this[j]]; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| 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. You assign the implementation to
or
Place this after the |
||
| }; | ||
| } | ||
|
|
||
|
|
||
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.
Consider adding an explicit type check for
compareFunctionso you throw a clear TypeError if a non-function is passed (the nativeArray.prototype.sortthrows whencompareFunctionis provided but not a function). This check could go at the start of the function body before usingcompareFunction.