Skip to content

Instantly share code, notes, and snippets.

@lexaurin
Created December 16, 2015 15:56
Show Gist options
  • Save lexaurin/a3cbe91124a2097bceb3 to your computer and use it in GitHub Desktop.
Save lexaurin/a3cbe91124a2097bceb3 to your computer and use it in GitHub Desktop.
Simple & elegant file size formatter
#!/usr/bin/env node
require('v8').setFlagsFromString('--harmony_destructuring');
const assert = require('assert');
function formatSizeSI(size) {
var index = Math.floor(Math.log(Math.abs(size)) / Math.log(1000)) | 0;
return +(size / Math.pow(1000, index)).toPrecision(3) + ' '
+ (index ? 'kMGTPEZY'[--index] + 'B' : 'Bytes');
}
[
[-5678000, '-5.68 MB'],
[-1, '-1 Bytes'],
[0, '0 Bytes'],
[1, '1 Bytes'],
[1234, '1.23 kB'],
[5678000, '5.68 MB'],
[80000001, '80 MB'],
[80060001, '80.1 MB'],
[180560001, '181 MB'],
[80000000000, '80 GB'],
['foo', 'NaN Bytes'],
].forEach(([actual, expected]) => assert.equal(formatSizeSI(actual), expected));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment