-
-
Save Deraen/03ace013ee571c2fe1d3 to your computer and use it in GitHub Desktop.
Humanize filesize
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
app.filter('bytes', function() { | |
return function(bytes, precision) { | |
if (isNaN(parseFloat(bytes)) || !isFinite(bytes)) return '-'; | |
if (typeof precision === 'undefined') precision = 1; | |
var units = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB']; | |
var number = Math.floor(Math.log(bytes) / Math.log(1024)); | |
return (bytes / Math.pow(1024, Math.floor(number))).toFixed(precision) + ' ' + units[number]; | |
}; | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns ... | |
(:require [goog.string :as gs]) | |
(def ^:private units ["bytes" "kB" "MB" "GB" "TB" "PB"]) | |
(def ^:private largest-unit (dec (count units))) | |
(def ^:private system 1000) ; or 1024 for binary sizes | |
(defn humanize-filesize | |
[bytes & [fmt]] | |
(let [unit (min largest-unit (js/Math.floor (/ (js/Math.log bytes) (js/Math.log system)))) | |
size (/ bytes (js/Math.pow system unit))] | |
(gs/format (or fmt "%0.1f %s") size (get units unit)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment