| 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 this.swarming = this.swarming || function() { | |
| 6 | |
| 7 var swarming = {}; | |
| 8 | |
| 9 // naturalCompare tries to use natural sorting (e.g. sort ints by value). | |
| 10 swarming.naturalCompare = function(a, b) { | |
| 11 // Try numeric, aka "natural" sort and use it if ns is not NaN. | |
| 12 // Javascript will try to corece these to numbers or return NaN. | |
| 13 var ns = a - b; | |
| 14 if (!isNaN(ns)) { | |
| 15 return ns; | |
| 16 } | |
| 17 return String(a).localeCompare(b); | |
| 18 }; | |
| 19 | |
| 20 | |
| 21 swarming.stableSort = function(arr, comp) { | |
| 22 if (!arr || !comp) { | |
| 23 console.log("missing arguments to stableSort", arr, comp); | |
| 24 return; | |
| 25 } | |
| 26 // We can guarantee a potential non-stable sort (like V8's | |
| 27 // Array.prototype.sort()) to be stable by first storing the index in the | |
| 28 // original sorting and using that if the original compare was 0. | |
| 29 arr.forEach(function(e, i){ | |
| 30 if (e !== undefined && e !== null) { | |
| 31 e.__sortIdx = i; | |
| 32 } | |
| 33 }); | |
| 34 | |
| 35 arr.sort(function(a, b){ | |
| 36 // undefined and null elements always go last. | |
| 37 if (a === undefined || a === null) { | |
| 38 if (b === undefined || b === null) { | |
| 39 return 0; | |
| 40 } | |
| 41 return 1; | |
| 42 } | |
| 43 if (b === undefined || b === null) { | |
| 44 return -1; | |
| 45 } | |
| 46 var c = comp(a, b); | |
| 47 if (c === 0) { | |
| 48 return a.__sortIdx - b.__sortIdx; | |
| 49 } | |
| 50 return c; | |
| 51 }); | |
| 52 } | |
| 53 | |
| 54 // postWithToast makes a post request and updates the error-toast | |
| 55 // element with the response, regardless of failure. See error-toast.html | |
| 56 // for more information. The body param should be an object or undefined. | |
| 57 swarming.postWithToast = function(url, msg, auth_headers, body) { | |
| 58 // Keep toast displayed until we hear back from the request. | |
| 59 sk.errorMessage(msg, 0); | |
| 60 | |
| 61 auth_headers["content-type"] = "application/json; charset=UTF-8"; | |
| 62 if (body) { | |
| 63 body = JSON.stringify(body); | |
| 64 } | |
| 65 | |
| 66 return sk.request("POST", url, body, auth_headers).then(function(response) { | |
| 67 sk.errorMessage("Request sent. Response: "+response, 3000); | |
| 68 return response; | |
| 69 }).catch(function(reason) { | |
| 70 console.log("Request failed", reason); | |
| 71 sk.errorMessage("Request failed. Reason: "+reason, 5000); | |
| 72 return Promise.reject(reason); | |
| 73 }); | |
| 74 } | |
| 75 | |
| 76 return swarming; | |
| 77 }(); | |
| OLD | NEW |