bytes.js icon indicating copy to clipboard operation
bytes.js copied to clipboard

Force convert to a level

Open ganna-shmatova opened this issue 10 years ago • 3 comments

ei, if I want to display disk usage. Used converts to 20 mb, max to 2tb. Be nice to be able to have them same unit.

something like:

var total = bytes(disk.total);
var used = bytes(disk.used, total); //or total.match(/[a-z]/i)

ganna-shmatova avatar Dec 05 '14 15:12 ganna-shmatova

@tj After the merge of the PR #20 I guess it won't be much trouble to add it as a second parameter.

For the bytes(number value, object [options]): string|null adding an property units which would result as the following:

bytes(1000, {units: null});
// output: '1000B'

bytes(1000, {units: 'kB'});
// output: '0.97656kB'

Which would also work with strings:

bytes('1MB', {units: 'kB'});
// output: '1024kB'

And maybe adding a shorthand:

bytes(1000,  'kB');
// output: '0.97656kB'

bytes('1MB', 'kB');
// output: '1024kB'

Which would be possible by determining if the options parameter is a string or an object. However that raises the case of what to do when the units passed are wrong? The current behavior is to return null which is unambiguous since if you do bytes('1ky'), the only error possible comes from the unit. But if you do so with bytes('1My', 'ku') or bytes('1mb', 'ku') we do not know from where the error comes from (although easy to guess).

Some possible solutions:

  • Keep the current behavior which returns null and let the user guess his error
  • Throw an error to display a more user friendly error, but I don't like the idea to have a try/catch for using this utility

I prefer the first solution.

theofidry avatar Mar 30 '15 08:03 theofidry

ping @dougwilson

theofidry avatar Feb 15 '16 23:02 theofidry

@theofidry, I'm impartial to the choice.

dougwilson avatar Feb 16 '16 02:02 dougwilson