Instantly share code, notes, and snippets.

@robozevel /Kilo.js
Last active Aug 29, 2015

Embed
What would you like to do?
/*
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