-
Notifications
You must be signed in to change notification settings - Fork 0
/
sort.html
92 lines (81 loc) · 1.93 KB
/
sort.html
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>.sort</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
</head>
<script>
$(function(){
var data1 = [
{name: 'Chuck', pinned: false},
{name: 'Don', pinned: false},
{name: 'Alex', pinned: false},
{name: 'Bob', pinned: true},
{name: 'Ed', pinned: false}
];
var data2 = {
e3: {name: 'Claire', pinned: false},
e4: {name: 'Dawn', pinned: false},
e1: {name: 'Ann', pinned: false},
e2: {name: 'Bea', pinned: false},
e5: {name: 'Erica', pinned: true}
};
function writeTo(data, $pre){
var output = '';
try {
$.each(data, function(i, o){
output+="{name: '"+
o.name+ // (Not safe but the data is)
"', pinned: "+(o.pinned?'true':false)+"}\n";
});
} catch (e) {
$pre.text("Non-iterable");
}
$pre.html(output);
}
function mySort(a,b){
if(a.pinned && (b.pinned == false)) {
return -1;
} else if(b.pinned && !a.pinned) {
return 1;
}
return a.name > b.name ? 1 : -1;
};
writeTo(data1, $('#input1'));
writeTo(data2, $('#input2'));
writeTo(data1.sort(mySort), $('#results1'));
try {
writeTo(data2.sort(mySort), $('#results2'));
} catch (e) {
if (e instanceof TypeError)
$('#results2').text('Can\'t .sort() a non-array. '+e);
else
$('#results2').text('Unexpected exception. '+e);
}
try {
var x = [];
$.each(data2, function(i, elem){
x.push(elem);
});
writeTo(x.sort(mySort), $('#results2p'));
} catch (e) {
$('#results2p').text('Unexpected exception. '+e);
}
});
</script>
<body>
<h1>.sort</h1>
<h3>Unsorted</h3>
<pre id="input1"></pre>
<h3>Sorted</h3>
<p><em>Pinned items should be first</em></p>
<pre id="results1"></pre>
<h3>Unsorted 2</h3>
<pre id="input2"></pre>
<h3>Sorted 2</h3>
<pre id="results2"></pre>
<h3>Sorted 2, proper</h3>
<pre id="results2p"></pre>
</body>
</html>