| 1 |
<!DOCTYPE html> |
| 2 |
<html> |
| 3 |
<head> |
| 4 |
<title></title> |
| 5 |
<script> |
| 6 |
// pasted in: |
| 7 |
/*** Copyright 2013 Teun Duynstee Licensed under the Apache License, Version 2.0 ***/ |
| 8 |
var firstBy=function(){function n(n){return n}function t(n){return"string"==typeof n?n.toLowerCase():n}function r(r,e){if(e="number"==typeof e?{direction:e}:e||{},"function"!=typeof r){var u=r;r=function(n){return n[u]?n[u]:""}}if(1===r.length){var i=r,o=e.ignoreCase?t:n;r=function(n,t){return o(i(n))<o(i(t))?-1:o(i(n))>o(i(t))?1:0}}return-1===e.direction?function(n,t){return-r(n,t)}:r}function e(n,t){return n=r(n,t),n.thenBy=u,n}function u(n,t){var u=this;return n=r(n,t),e(function(t,r){return u(t,r)||n(t,r)})}return e}(); |
| 9 |
|
| 10 |
// sample: |
| 11 |
var data = [ |
| 12 |
{ id: 7, name: "Amsterdam", population: 750000, country: "Netherlands" }, |
| 13 |
{ id: 12, name: "The Hague", population: 450000, country: "Netherlands" }, |
| 14 |
{ id: 43, name: "Rotterdam", population: 600000, country: "Netherlands" }, |
| 15 |
{ id: 5, name: "Berlin", population: 3000000, country: "Germany" }, |
| 16 |
{ id: 42, name: "D�sseldorf", population: 550000, country: "Germany" }, |
| 17 |
{ id: 44, name: "Stuttgard", population: 600000, country: "Germany" }, |
| 18 |
]; |
| 19 |
function output() { |
| 20 |
for (var i = 0; i < data.length; i++) { |
| 21 |
document.write(data[i].name + "<br/>"); |
| 22 |
} |
| 23 |
document.write("<br/>"); |
| 24 |
} |
| 25 |
output(); |
| 26 |
|
| 27 |
// first by country, then by pop, should give D�sseldorf first, Amsterdam last |
| 28 |
var s = firstBy(function (v1, v2) { return v1.country < v2.country ? -1 : (v1.country > v2.country ? 1 : 0); }) |
| 29 |
.thenBy(function (v1, v2) { return v1.population - v2.population; }); |
| 30 |
data.sort(s); |
| 31 |
output(); |
| 32 |
// first by length of name, should give Stuttgard just after Rotterdam (same length, same pop) |
| 33 |
s = firstBy(function (v1, v2) { return v1.name.length - v2.name.length; }) |
| 34 |
.thenBy(function (v1, v2) { return v1.population - v2.population; }) |
| 35 |
.thenBy(function (v1, v2) { return v1.id - v2.id; }); |
| 36 |
data.sort(s); |
| 37 |
output(); |
| 38 |
|
| 39 |
// Now we do the same, but using some handy shortcuts |
| 40 |
// first by country, then by pop, should give D�sseldorf first, Amsterdam last |
| 41 |
var s = firstBy("country").thenBy("population"); |
| 42 |
data.sort(s); |
| 43 |
output(); |
| 44 |
// first by length of name, should give Stuttgard just after Rotterdam (same length, same pop) |
| 45 |
s = firstBy(function (v) { return v.name.length;}) |
| 46 |
.thenBy("population") |
| 47 |
.thenBy("id"); |
| 48 |
data.sort(s); |
| 49 |
output(); |
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
</script> |
| 54 |
</head> |
| 55 |
<body> |
| 56 |
</body> |
| 57 |
</html> |