Skip to content

Instantly share code, notes, and snippets.

@yairEO
Created September 28, 2017 09:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yairEO/4747208b23ab7d4b4db404e86d178652 to your computer and use it in GitHub Desktop.
Save yairEO/4747208b23ab7d4b4db404e86d178652 to your computer and use it in GitHub Desktop.
lodash "formatBytes" mixin
_.mixin({
"formatBytes" : function(kiloBytes, decimals){
if(kiloBytes == 0) return ['0', 'KB'];
var k = 1024,
dm = decimals + 1 || 1,
sizes = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
i = Math.floor(Math.log(kiloBytes) / Math.log(k));
return [parseFloat((kiloBytes / Math.pow(k, i)).toFixed(dm)).toLocaleString() , sizes[i]]; // parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' +
},
"orderByAaBb" : function(arr, prop){
var clonedArr = _.cloneDeep(arr);
return clonedArr.sort((a,b) => a[prop].localeCompare(b[prop], 'en-US-u-kf-upper'));
}
});
@yairEO
Copy link
Author

yairEO commented Sep 28, 2017

Usage:

_.formatBytes(123456789).join(' ')  // => "117.7 GB"

Accepts number or string which represents a number

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment