Last active
August 29, 2015 13:56
-
-
Save robozevel/8897895 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
/* | |
Kilo.js | |
#toSize: 2048 => "2 KB" | |
#toBytes: "2 KB" => 2048 | |
*/ | |
var Kilo = (function() { | |
"use strict"; | |
var kilo = 1024; | |
var sizes = { "B": 0, "KB": 1, "MB": 2, "GB": 3, "TB": 4 }; | |
var sizesNames = Object.keys(sizes); | |
var rSize = /(\d+)\s*(B|KB|MB|GB|TB)*/i; | |
function isNaN(value) { | |
return value !== value; | |
}; | |
return { | |
// Based on: http://scratch99.com/web-development/javascript/convert-bytes-to-mb-kb/ | |
toSize: function(bytes, digits, separator) { | |
var isNegative = false; | |
if (bytes === 0 || isNaN(bytes)) return 'n/a'; | |
if (bytes < 0) isNegative = true, bytes *= -1; | |
var i = Number(Math.floor(Math.log(bytes) / Math.log(kilo))); | |
bytes = i === 0 ? bytes : (bytes / Math.pow(kilo, i)).toFixed(digits >= 0 ? digits : 2); | |
return (isNegative ? "-" : "") + [bytes, sizesNames[i]].join(typeof separator === "string" ? separator : " "); | |
}, | |
toBytes: function(size, unit) { | |
var match = rSize.exec(size); | |
return !match ? NaN : Number(match[1]) * (match[2] ? Math.pow(kilo, sizes[match[2].toUpperCase()]) : 1); | |
} | |
}; | |
}()); | |
function toSize(bytes, digits, separator) { | |
return Kilo.toSize(bytes, digits, separator); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment