Skip to content

Instantly share code, notes, and snippets.

@huzemin
Last active January 18, 2016 14:30
Show Gist options
  • Save huzemin/f1c0b4fb92b8eb90747f to your computer and use it in GitHub Desktop.
Save huzemin/f1c0b4fb92b8eb90747f to your computer and use it in GitHub Desktop.
Normalize file size description
/**
* @author huzemin8 <[email protected]>
*/
/**
* @param in_size mixed file size
* @param type string output size
* @param precision int
* @return string
*/
function size_normalize(in_size, type, precision) {
var size = '', byte = 0;
var p = /^\s*(\d+)\s?(\w+)?\s?/;
// 精度
if(precision == undefined) {
precision = 2;
}
if(type !== undefined) {
type = type.toUpperCase();
} else {
type = 'B';
}
if(isNaN(in_size)) {
var in_type = '';
var match = in_size.match(p);
if(match) {
byte = parseFloat(match[1]);
if(match[2] != undefined) {
var toByte = {
'bits' : 8,
'b' : 1,
'kb' : 1024,
'mb' : 1024 * 1024,
'GB' : 1024 * 1024 * 1024
};
in_type = match[2].toLowerCase();
if(toByte[in_type] != undefined) {
byte = byte * toByte[in_type];
}
}
} else {
throw new Error('Unrecognized size');
}
} else {
byte = in_size;
}
switch(type) {
case 'B':
size = byte + type;
break;
case 'KB':
size = (byte / 1024).toFixed(precision) + type;
break;
case 'MB':
size = (byte / 1024 / 1024).toFixed(precision) + type;
break;
case 'GB':
size = (byte / 1024 / 1024 / 1024).toFixed(precision) + type;
break;
default:
size = byte * 8 + 'bits'
}
return size;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment