Instantly share code, notes, and snippets.

Embed
What would you like to do?
Takes a file size and rewrites it with the appropriate suffix (eg. MB, GB, etc.).
/**
* Used to make a file size human readable. Takes the number of bytes or bits
* and converts it into a string indicating the number in the appropriate
* range (eg. KB, MB, etc.).
* @name suffixFileSize
* @function
* @param {number} count
* Number of bytes or bits to represent as a string.
* @param {boolean} [opt_countInBits=false]
* Specifies whether `count` is given in bits instead of bytes.
* @returns {string}
* A string indicating `count` with the appropriate measure (eg. kb, Mb,
* etc.).
*/
var suffixFileSize;
(function(Math, SUFFIXES) {
suffixFileSize = function(count, opt_countInBits) {
var div = opt_countInBits ? 3 : 10,
base = opt_countInBits ? 10 : 2,
level = ~~Math.min(Math['log' + base](count < 0 ? -count : count) / div, 8);
count = (count / Math.pow(base, div * level)).toFixed(2).replace(/\.?0+$/, '')
+ ' ' + SUFFIXES[level];
return opt_countInBits ? count : count.toUpperCase();
};
})(Math, ['b','kb','Mb','Gb','Tb','Pb','Eb','Zb','Yb']);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment