Skip to content

Instantly share code, notes, and snippets.

@Deraen
Forked from thomseddon/gist:3511330
Last active July 5, 2017 15:14
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Deraen/03ace013ee571c2fe1d3 to your computer and use it in GitHub Desktop.
Save Deraen/03ace013ee571c2fe1d3 to your computer and use it in GitHub Desktop.
Humanize filesize
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];
};
});
(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