Chromium Code Reviews| OLD | NEW |
|---|---|
| (Empty) | |
| 1 // Copyright 2016 The LUCI Authors. All rights reserved. | |
| 2 // Use of this source code is governed under the Apache License, Version 2.0 | |
| 3 // that can be found in the LICENSE file. | |
| 4 | |
| 5 window.swarming = window.swarming || function() { | |
| 6 var swarming = {}; | |
| 7 | |
| 8 swarming.stableSort = function(arr, comp) { | |
| 9 if (!arr || !comp) { | |
| 10 console.log("missing arguments to stableSort", arr, comp); | |
| 11 return; | |
| 12 } | |
| 13 // We can guarantee a potential non-stable sort (like V8's | |
| 14 // Array.prototype.sort()) to be stable by first storing the index in the | |
| 15 // original sorting and using that if the original compare was 0. | |
| 16 arr.forEach(function(e, i){ | |
| 17 if (e !== undefined && e !== null) { | |
| 18 e.__sortIdx = i; | |
| 19 } | |
| 20 }); | |
| 21 | |
| 22 arr.sort(function(a, b){ | |
| 23 // undefined and null elements always go last. | |
| 24 if (a === undefined || a === null) { | |
| 25 if (b === undefined || b === null) { | |
| 26 return 0; | |
| 27 } | |
| 28 return 1; | |
| 29 } | |
| 30 if (b === undefined || b === null) { | |
| 31 return -1; | |
| 32 } | |
| 33 var c = comp(a, b); | |
| 34 if (c === 0) { | |
| 35 return a.__sortIdx - b.__sortIdx; | |
| 36 } | |
| 37 return c; | |
| 38 }); | |
| 39 } | |
| 40 | |
| 41 // naturalCompare tries to use natural sorting (e.g. sort ints by value). | |
| 42 swarming.naturalCompare = function(a, b) { | |
| 43 // Try numeric, aka "natural" sort and use it if ns is not NaN. | |
| 44 // Javascript will try to corece these to numbers or return NaN. | |
|
jcgregorio
2016/08/01 14:04:36
nit: coerce
| |
| 45 var ns = a - b; | |
| 46 if (ns) { | |
| 47 return ns; | |
| 48 } | |
| 49 return a.localeCompare(b); | |
| 50 } | |
| 51 | |
| 52 return swarming; | |
| 53 }(); | |
| OLD | NEW |