This is a function to calculate the appropriate unit to describe a file size. If you want a fancier function, try this function: https://gist.github.com/2202887 by @vitronprince
Thanks to maettig for minification tips.
This is a function to calculate the appropriate unit to describe a file size. If you want a fancier function, try this function: https://gist.github.com/2202887 by @vitronprince
Thanks to maettig for minification tips.
function( | |
a, //number | |
c //placeholder | |
) | |
{ | |
for(;a>>10;c=-~c)a>>=10; //as long the number is over 1023, divide it by 1024 | |
//a>>10 is the same as a/1024 (Thanks maettig!) | |
//also set a counter to +1 | |
return a+(" kMGT"[c]||"")+"B"} //return final number + the suffix |
function(a,c){for(;a>>10;c=-~c)a>>=10;return a+(" kMGT"[c]||"")+"B"} | |
Shorter version using proper unicode unit symbols: | |
function(a,c){for(;a>>10;c=-~c)a>>=10;return a+(" ㎅㎆㎇"[c]||"B")} |
{ | |
"name": "fileSizeUnits", | |
"description": "Function to calculate the appropriate unit to describe a file size", | |
"keywords": [ | |
"file", | |
"size", | |
"units", | |
"math" | |
] | |
} |
<!DOCTYPE html> | |
<title>file Size Unit Calculator</title> | |
<div>Expected value: <b>269MB</b></div> | |
<div>Actual value: <b id="ret"></b></div> | |
<script> | |
var fileSizeUnits = function(a,c){for(;a>>10;c=-~c)a>>=10;return a+(" kMGT"[c]||"")+"B"} | |
document.getElementById( "ret" ).innerHTML = fileSizeUnits(282630144) | |
</script> |
@maettig
GENIUS!
right shift operator ftw!
not sure about "[c|0]" tho... "|" isn't the same as "||"
example:
20||18 = 20
20|18 = 22
Yea, but it's |0
. It's there because c may be "undefined" and must be converted to "0". You can do the same with ~~c
.
Edit: I'm wondering about the space. Is it intended to have a space in "15 B" but not in "15MB"?
@maettig quote:"I'm wondering about the space. Is it intended to have a space in "15 B" but not in "15MB"?"
Oops! Thats a bug alright, I'll go and fix it. :P
Edit: Fixd!
What about this? Saves 3 bytes. I'm not sure if it works in all cases.