From 0f4ddbd155860a73ed32f1a71e9435ef0c09eb65 Mon Sep 17 00:00:00 2001 From: Nils Maier Date: Sun, 23 Feb 2014 22:59:26 +0100 Subject: [PATCH] Improve bytes formatting. Also may or may not perform a bit better. Most likely the former. --- js/filters/bytes.js | 81 ++++++++++++++++++++++++--------------------- 1 file changed, 44 insertions(+), 37 deletions(-) diff --git a/js/filters/bytes.js b/js/filters/bytes.js index aaf9654..6765ab1 100644 --- a/js/filters/bytes.js +++ b/js/filters/bytes.js @@ -1,40 +1,47 @@ -angular -.module('webui.filters.bytes', []) -.filter('changeLength', function() { - return function(len, pref) { - len = parseFloat(len); - if (len <= (1<<10)) return len.toFixed(1) + " " + pref; - else if(len <= (1<<20)) return (len/(1<<10)).toFixed(1) + " K" + pref; - else if(len <= (1<<30)) return (len/(1<<20)).toFixed(1) + " M" + pref; - else return (len/(1<<30)).toFixed(1) + " G" + pref; - }; -}) -.filter('blength', ['$filter', function(filter) { - return function(len) { - return filter('changeLength')(len, 'B'); - }; -}]) -.filter('bspeed', ['$filter', function(filter) { - return function(speed) { - return filter('changeLength')(speed, 'B/s'); - }; -}]) -.filter('time', function() { - function pad(f) { - return ("0" + f).substr(-2); +(function() { + function fmtlen(len) { + len = +len; // coerce to number + if (len <= 1024) { + return len.toFixed(0) + " B"; + } + len /= 1024; + if (len <= 1024) { + return len.toFixed(1) + " KB" + } + len /= 1024; + if (len <= 1024) { + return len.toFixed(2) + " MB"; + } + len /= 1024; + return len.toFixed(3) + " GB"; } - return function(time) { - time = parseInt(time, 10); - if (!time || !isFinite(time)) return "∞"; - var secs = time % 60; - if (time < 60) return secs + "s"; - var mins = Math.floor((time % 3600) / 60) - if (time < 3600) return pad(mins) + ":" + pad(secs); - var hrs = Math.floor((time % 86400) / 3600); - if (time < 86400) return pad(hrs) + ":" + pad(mins) + ":" + pad(secs); - var days = Math.floor(time / 86400); - return days + "::" + pad(hrs) + ":" + pad(mins) + ":" + pad(secs); - }; -}); + angular .module('webui.filters.bytes', []) + .filter('blength', ['$filter', function(filter) { + return fmtlen; + }]) + .filter('bspeed', ['$filter', function(filter) { + return function(speed) { + return fmtlen(speed) + "/s"; + }; + }]) + .filter('time', function() { + function pad(f) { + return ("0" + f).substr(-2); + } + + return function(time) { + time = parseInt(time, 10); + if (!time || !isFinite(time)) return "∞"; + var secs = time % 60; + if (time < 60) return secs + "s"; + var mins = Math.floor((time % 3600) / 60) + if (time < 3600) return pad(mins) + ":" + pad(secs); + var hrs = Math.floor((time % 86400) / 3600); + if (time < 86400) return pad(hrs) + ":" + pad(mins) + ":" + pad(secs); + var days = Math.floor(time / 86400); + return days + "::" + pad(hrs) + ":" + pad(mins) + ":" + pad(secs); + }; + }); +})();