Last active
May 17, 2024 03:10
-
-
Save cmc19/9670351 to your computer and use it in GitHub Desktop.
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
//adapted from https://github.com/kapouer/bytes.js | |
var util = util || {}; | |
(function (util) { | |
function bytes(size) { | |
if ('number' == typeof size) return convert(size); | |
var parts = size.match(/^(\d+(?:\.\d+)?) *(kb|mb|gb)$/i), | |
n = parseFloat(parts[1]), | |
type = parts[2].toLowerCase(); | |
var map = { | |
kb: 1 << 10, | |
mb: 1 << 20, | |
gb: 1 << 30 | |
}; | |
return map[type] * n; | |
/** | |
* convert bytes into string. | |
* | |
* @param {Number} b - bytes to convert | |
* @return {String} | |
* @api public | |
*/ | |
function convert(b) { | |
var gb = 1 << 30, | |
mb = 1 << 20, | |
kb = 1 << 10; | |
if (b >= gb) return (Math.round(b / gb * 100) / 100) + 'GB'; | |
if (b >= mb) return (Math.round(b / mb * 100) / 100) + 'MB'; | |
if (b >= kb) return (Math.round(b / kb * 100) / 100) + 'KB'; | |
return b + 'B'; | |
} | |
}; | |
util.bytes = bytes; | |
})(util); |
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
util.bytes(1024* 1024 * 1.5) // => 1.5MB |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment