-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsort.js
More file actions
42 lines (35 loc) · 998 Bytes
/
sort.js
File metadata and controls
42 lines (35 loc) · 998 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Array.prototype.sort
* The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted.
*/
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]
const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]
// Calls
// Functionless
sort()
// Compare function
sort(compareFn)
function defaultComparator(a, b) {
a = a.toString();
b = b.toString();
if (a < b) return -1;
else if (a > b) return 1;
else return 0
}
Array.prototype.mySort = function (compareFn = defaultComparator) {
for (let i = 0; i < this.length; i++) {
for (let j = i + 1; j < this.length; j++) {
// swap only when a>b
if (compareFn(this[i], this[j]) > 0) {
[this[i], this[j]] = [this[j], this[i]]
}
}
}
return this;
}